Reputation: 439
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!
Upvotes: 1
Views: 1554
Reputation: 1101
I was running into a similar problem. Mine was resolved by returning a promise. I think sequelize is expecting a promise to be returned. It will wait until a promise is resolved or rejected. If a promise is not return I think it assumes everything is "done" and "good". Your first example is not returning a promise. it just "runs" and exists without waiting for all the async code to complete (aka User.findAll()).
Solution: I think if you return a promise in your up method and resolve it when you are "done" I think that will work. Example:
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)
});
}
},
Upvotes: 1