Creating instead of Updating" with Sequelize Upsert

I’m trying to use upsert to insert or update a single row in my database using a unique key. However, instead of updating the existing record, my code is adding a new record. What am I doing wrong?

My model is defined as follows:

'use strict'

module.exports = (db, dataTypes) => {
  const titanJob = db.define('titanJob', {
    titanId: {
      type: dataTypes.STRING,
      allowNull: false,
      unique: true
    },
    name: {
      type: dataTypes.STRING,
      allowNull: false
    }
  }, {
    timestamps: true
  })
  return titanJob
}

and this is the upsert code:

await asyncForEach(res.data.hits.hits, async es => {
  const src = es._source
  try {
    await titanJob.upsert({
      name: src.name,
      titanId: src.id,
    }, { titanId: src.id })
    logger.debug(`[${file}] upsert successful`)
  } catch (err) {
    logger.warn(`[${file}] failed to save to database`)
    logger.warn(`[${file}] ${err}`)
  }
})

I’m getting a new record instead of updating the existing one when using upsert with a unique key. What am I doing wrong?

The issue is with the order of the arguments in the upsert function. The second argument should be the object to be inserted or updated, and the first argument should be the object specifying the unique key. Therefore, the upsert code should be modified as follows:

await asyncForEach(res.data.hits.hits, async es => {
  const src = es._source
  try {
    await titanJob.upsert({
      titanId: src.id // specify the unique key first
    }, {
      name: src.name,
      titanId: src.id,
    })
    logger.debug(`[${file}] upsert successful`)
  } catch (err) {
    logger.warn(`[${file}] failed to save to database`)
    logger.warn(`[${file}] ${err}`)
  }
})

This should update the existing record with the specified unique key, or insert a new record if it does not exist.