Getting data from MongoDB with Mongoose Getting data from MongoDB with Mongoose mongoose mongoose

Getting data from MongoDB with Mongoose


Ah this is a nice one, you're trying to do something in an synchronous style:

Users.find({}, function (err, user){  // here you are iterating through the users  // but you don't know when it will finish});// no users here because this gets called before any user// is inserted into the arrayconsole.log(returnObject); 

Instead you should do something like this:

var callback = function (obj) {  console.log(obj);}Users.find({}, function (err, user){  var counter = user.length;  _.each(user, function(userDoc) {    if (counter) {      returnObject.list.push(userDoc);                // we decrease the counter until       // it's 0 and the callback gets called      counter--;    } else {      // since the counter is 0      // this means all the users have been inserted into the array      callback(returnObject);    }  });});


do a util.inspect(user) to see what you have before the each loop.