1

I have 2 related tables, and i want seed on that tables. The users seeder is working fine, and on my second seeder file I query all the users then attached every users on users_information table. Here is my code.

var chance = require('chance').Chance();
const User = require('../models/User');

module.exports = {
  up: function (queryInterface, Sequelize) {
    User.findAll()
      .then(users => {
        var usersInfo = [];
        for(let user of users) {
          var userInfo = {
            user_id: user.id,
            first_name: user.username,
            middle_name: chance.last(),
            last_name: chance.last(),
            address: chance.address()
          };
          usersInfo.push(userInfo);
        }

        return queryInterface.bulkInsert('users_information', usersInfo);
      })
      .catch(error => console.error(error));
  },

  down: function (queryInterface, Sequelize) {
      return queryInterface.bulkDelete('users_information', null, {});
  }
};

when i run db:seed:all command it runs without an error and the data on users_information table is empty.

The seeder is working without a model query. Just to test if my seeder file works.

up: function (queryInterface, Sequelize) {
     var usersInfo = [];

     for(var i = 1; i <= 10; i++) {
       var userInfo = {
         user_id: i,
         first_name: chance.first(),
         middle_name: chance.last(),
         last_name: chance.last(),
         address: chance.address()
       };
       usersInfo.push(userInfo);
     }
     return queryInterface.bulkInsert('users_information', usersInfo);
},

here's my tables

users table

- id (PK)
- username
- user_type
- is_active

users_information table

- id (PK)
- user_id (FK)
- first_name
- last_name
- address

Any suggestions or idea? Thanks!

4

1 回答 1

0

我遇到了类似的问题。我的问题是通过返回一个承诺来解决的。我认为sequelize 期望得到回报。它将等到一个承诺被解决或被拒绝。如果一个承诺没有得到回报,我认为它假设一切都“完成”和“好”。您的第一个示例没有返回承诺。它只是“运行”并存在而无需等待所有异步代码完成(又名 User.findAll())。

解决方案: 我认为如果您在up方法中返回一个承诺并在“完成”时解决它,我认为这会起作用。例子:

  up: function (queryInterface, Sequelize) {
    // return a new promise that sequelize will wait for...
    return new Promise((resolve, reject)=>{
         User.findAll()
              .then(users => {
                var usersInfo = [];
                for(let user of users) {
                  var userInfo = {
                    user_id: user.id,
                    first_name: user.username,
                    middle_name: chance.last(),
                    last_name: chance.last(),
                    address: chance.address()
                  };
                  usersInfo.push(userInfo);
                }
                // Notice we are not returning this.
                queryInterface.bulkInsert('users_information', usersInfo);
                resolve('Done');
              })
              .catch((error) => {
                console.error(error);
                reject(error)
              });
    }
  },
于 2018-12-16T05:48:34.450 回答