Search code examples
node.jssequelize.jssequelize-cli

find records in sequelize seeds


I've been trying to write some seeds for my project, but I've ran into a bit of a snag.

I've got a many-to-many relation with my users and roles table. So, when I'm seeding the database I need to add a record with correct ids into my join table. In order to do that I need to find user by email and role by name and get the ids and that's the problem. I can't find any good documentation on the sequelize site. I'm using the sequelize-cli for the seeding and migrating things. I get as a parameter a queryInterface, but I can't find any example or mention what this thing can actually do. Just some simple examples just got me through the migrating (somehow) and what I was able to find on google.

I've resolved this by using a "dirty trick" I'd say...

// user_seeds.js
up: function (queryInterface, Sequelize) {
  return queryInterface.bulkInsert(table, [{
    id: 1,
    name: 'John doe',
    email: '[email protected]',
    created_at,
    updated_at
}], {});

// roles_seeds.js
up: function (queryInterface, Sequelize) {
  return queryInterface.bulkInsert(table, [{
    id: 1,
    name: 'admin',
    created_at,
    updated_at
  }, {
    id: 2,
    name: 'user',
    created_at,
    updated_at
}]);

//user_roles_seeds.js
up: function (queryInterface, Sequelize) {
    return queryInterface.bulkInsert(table, [{
    employee_id: 1,
    role_id: 1
  }]);
},

Don't like this solution since it may be troublesome in the future should I'd want to run the seeds again and forget about how this works. There should be a way for me to query the database using this queryInterface. I was wondering if one of you had ran into this issue and solved it, if so, please share.


Solution

  • Yes you can use the queryInterface to query database.

      async up(queryInterface, Sequelize) {
        const user = await queryInterface.rawSelect('User', {
          where: {
            name: 'John doe',
          },
        }, ['id']);
    
        if(!user) {
           // do bulkInsert stuff.
        }
      },