Greg Brunk Greg Brunk - 1 year ago 69
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, ) isn't actually saving records.

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


// 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 = user_list[i].email;
newUser.password = createHash(user_list[i].password); = user_list[i].company;
newUser.firstName = user_list[i].firstName;
newUser.lastName = user_list[i].lastName;
newUser.admin = user_list[i].admin;
// save the user, users) {
if (err){
console.log('Error in Saving user: '+ err);
throw err;
console.log("created", user_list.length, "users");

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download