codejunkie
codejunkie

Reputation: 968

Sequelize findOrCreate returns SequelizeUniqueContraintError on a model with an additional unique keys

I am using Sequelize with NodeJS and MySql. (latest versions)

I have a user model with -

  1. 'id' and unique and primary key. 'id' is set to auto increment.
  2. some user details such as firstName, lastName, email etc.
  3. Two additional unique keys (marked as unique in the sequelize model and in the database) - 'username' and 'email'

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

Answers (1)

codejunkie
codejunkie

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

Related Questions