Skip to content Skip to sidebar Skip to footer

How Do You Do A "join" On An Array In Mongoose (mongodb) With Node.js?

How do you do a 'join' (i know it is not the correct term) with an array of messages in mongoose? I tried looping over all the messages and querying to get the user info but it is

Solution 1:

the biggest problem with your code is, that you assume the code to run synchronously - but it doesn't. it runs asynchronously. so messages is not yet set when you execute

 console.log(messages);

do something like this instead:

var userIds = [id1, id2, id3];
User.find({"_id": {$in: userIds}}, function (err, users) {
  console.log(users);
});

edit ok, i see. you want to add the userInfo to the different messages. easiest way to acieve this, is to use the async module: https://github.com/caolan/async

async.map(messages, getUserInfo, function (err, result) {
  if (err) {
    console.log(err);
    return;
  }
  // log all msg with userinfoconsole.log(result);
});

functiongetUserInfo (msg, callback) {
  User.findById(msg.userId, function (err, user) {
    if (err) {
       callback(err);
       return;
    }
    msg.user = user;
    callback(null, msg);
  });
}

Post a Comment for "How Do You Do A "join" On An Array In Mongoose (mongodb) With Node.js?"