1

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 not working:

messages.forEach(function (message, index) {
  User.findById(message.userId, function (err, user) {
    messages[index].user = user
  })
})

console.log(messages) // the user info is not attatched

So how is this accomplished with mongoose and node.js?

1
  • You want to push messages var to a new array or make an implode of messages ? Commented Jul 27, 2011 at 6:22

1 Answer 1

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 userinfo
  console.log(result);
});

function getUserInfo (msg, callback) {
  User.findById(msg.userId, function (err, user) {
    if (err) {
       callback(err);
       return;
    }
    msg.user = user;
    callback(null, msg);
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

yeah, "$in" finds the list of users that sent those messages, but I can't think of a simple way of adding it to the message so that instead of [{message:'blah', userId:'dsfsdf'}, ....] it would be [{message:'blah', user:{user info here}, ....]
@guy-guy ok, didn't get this at first glance. edited my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.