Greg Brunk Greg Brunk - 3 months ago 11
Node.js Question

Mongoose .create( ) not saving entries to db

My seed file is supposed to seed 2 users into my MongoDB. My db.User.remove( ) is definitely deleting any existing users in my db, so I am accessing the right db. However, newUser.save( ) isn't actually saving records.

My console.log is showing that my 2 user objects from user_list have been generated, but my newUser.save( ) is not actually saving new records to the User collection (it's completely empty). Any ideas?

seed.js

// remove all users
db.User.remove({}, function(err, users){
if(err) {
console.log('Error occurred in remove', err);
} else {
console.log('removed all users');
// create new records based on the array user_list
for (i=0; i < user_list.length; i++) {
var newUser = new User();
// set the user's local credentials
newUser.email = user_list[i].email;
newUser.password = createHash(user_list[i].password);
newUser.company = user_list[i].company;
newUser.firstName = user_list[i].firstName;
newUser.lastName = user_list[i].lastName;
newUser.admin = user_list[i].admin;
console.log(newUser);
// save the user
newUser.save(function(err, users) {
if (err){
console.log('Error in Saving user: '+ err);
throw err;
}
});
}
console.log("created", user_list.length, "users");
process.exit();
}
});

Answer

save operation is asynchronous(non-blocking) and as a result, process.exit(); will be executed earlier then save operation. user_list seems to an array with static data. Try to log users variable or just any marker in save callback instead.

The way to fix it is to aggregate and use promises or place check for the last user in save callback.

Comments