ryanmc ryanmc - 16 days ago 15
MySQL Question

how do I use sequelize findorcreate defaults

I am trying to use the findorcreate method in sequelize and it correctly inserts a row in my mysql database, but the values I put in the defaults section are not getting inserted.

Here is my code

return userDb
.findOrCreate({
defaults: {
first_name: 'john',
last_name: 'doe',
email: 'test@test.com'
},
where: {
user_id:UserId
}
})


here is the insert statement that the debug outputs

INSERT INTO `user` (`id`,`user_id`,`deleted`,`created_on`) VALUES (DEFAULT,200,'0',NOW());


as you can see it does not even attempt to insert the 3 fields I have in the default section. Am I missing something?

Answer

The fields that you are seeing in the INSERT are all default columns that Sequelize creates for a Model/table, so likely the User Sequelize Model is not defined properly. Because the Model doesn't contain these columns, the fields you are specifying in defaults cannot be applied.

Make sure that you define first_name, last_name, and email in the Sequelize.define() for your User Model.

const sequelize = new Sequelize();
const User = sequelize.define(
  'user',
  {
    first_name: {
      type: Sequelize.STRING,
    },
    last_name: {
      type: Sequelize.STRING,
    },
    email: {
      type: Sequelize.STRING,
    },
  }
);