Reputation: 797
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?
Upvotes: 11
Views: 18039
Reputation: 1147
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
Upvotes: 1
Reputation: 11677
.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.
Upvotes: 22