Difference between findOrCreate () and upsert () in sequelize

I read over the document and he mentioned two ways to do upsert: findOrCreate() or upsert() . I read the descriptions, but I still don't understand what the difference is.

upsert() continues:

 Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated. 

Does this mean that upsert() explicitly requires the definition of the primary id UNIQUE field in my model? i.e:

 var Something = sequelize.define("Something", { id: { type: DataTypes.INTEGER, primaryKey: true, unique: true, allowNull: false}}); 

If so, why does findOrCreate() not have this limitation?

Can someone explain the use cases when using findOrCreate() and upsert() and why upsert() has a unique restriction requirement when findOrCreate() doesn't seem to need it?

+6
source share
1 answer

.findOrCreate will query the database with the parameters you provided, and if there is no match, it will perform an insert operation using the same parameters. At the same time, the .upsert point should either update or insert a record. In the case of an update operation, the logic requires that you look for a record based on a unique key, and only after you find this unique record, update its values ​​based on the provided parameters. If you cannot find a unique entry, only then would you insert.

Hope this makes sense.

+13
source

Source: https://habr.com/ru/post/981800/


All Articles