Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between findOrCreate() and upsert() in sequelize

I was reading over the doc and it mentioned two ways of doing an upsert: findOrCreate() or upsert(). I read the descriptions, but I'm still not clear what the difference is.

The upsert() goes on to say:

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 upsert() explicitly requires I define an id UNIQUE primary field in my model? ie:

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

If so, why does findOrCreate() not have that restriction?

Can someone explain the use cases for when findOrCreate() and upsert() should be used, and why upsert() has the unique constraint requirement when findOrCreate() doesn't seem to need it?

like image 436
fanhats Avatar asked Jan 31 '15 07:01

fanhats


People also ask

What does Upsert do in Sequelize?

The upsert() method accepts an object of data with the property keys serving as the column names and the property values as the column values. The method would then return an array of two elements: The instance the Model where you call the method, returning the new/updated row.

How do I use update in Sequelize?

The Model. upsert() method is a new method added in Sequelize v6 that allows you to perform an update statement only when a row with matching values already exist. To update a row, you need to specify the primary key of the row, which is the id column in case of the Users table.


2 Answers

.findOrCreate will query the database with the parameters you provided, and if there is no match, it will perform an insert operation using those same parameters. Whereas the point of an .upsert, is to either update or insert a record. In the case of an update operation, logic dictates that you look for a record based on a unique key, and only once you find this unique record, update its values based on the parameters provided. If you aren't able to find a unique record, only then would you perform an insert.

I hope that makes sense.

like image 87
Yuri Zarubin Avatar answered Nov 12 '22 03:11

Yuri Zarubin


the key difference is Id field. In case of upsert you need the id field. But sometimes, you dont hv the id field. For example when creating a user from an external provider fields say fb, you will not have the id of the user record if it already exists. In this case you will have to use findOrCreate on one of the fields returned by fb like for example email. findOrCreate user where the email is the email returned from fb

like image 34
noob7 Avatar answered Nov 12 '22 03:11

noob7