Reputation: 968
I am using Sequelize with NodeJS and MySql. (latest versions)
I have a user model with -
I am using the 'findOrCreate' method to create or lookup. My code creates a record if it does not exist but throws a UniqueConstraintError (ER_DUP_ENTRY) --> SequelizeUniqueContraintError on the "username" field when I try to find this record. Basically, the findOrCreate tries to create a record for the second time instead of finding it.
I was able to fix this issue by manually doing a find and if not found then create. But I need the flag returned by the 'findOrCreate' method which helps determine whether a record was created or found.
Can someone please help?
Upvotes: 4
Views: 5688
Reputation: 968
I was able to resolve this by passing the unique key to the 'findOrCreate' method of the model in the 'where' clause and setting values for all other table attributes in the 'defaults' clause.
For Eg. - Employee.findOrCreate({where: {employeeId: 'ABCD1234'}, defaults: {role: 'Analyst'}});
Where employeeId is a Unique Key. (I assume that the primary key 'id' field is set to Auto Increment)
Please refer to the example provided in the official tutorial. here
Upvotes: 5