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?
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
do something like this instead:
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