I'm using Node.js and mongoose to query a mongodb database. It is very simple scenario but I cannot figure out how to do it properly.
I have a collection to query and then given the result, need to fetch object from another collection to populate the result. code sample as below:
q.exec( function (e, docs){
if (e || !docs) {
res.status(400);
res.send("Error while processing request.\n"+ JSON.stringify(e, null, 4));
}else{
//do the JOIN here.
var result = _(docs).map(
function(doc){
markModel.findOne(
{question_id: doc._id, user_id: user_id},
function (err, markDoc){
if (markDoc)
doc.mark = markDoc;
});
//HOW and what to return here??
});
res.send(result);
}
});
In the code above, docs
is the result of the first query; and then I need to find the mark
from another collection for each of the doc
in docs
, and attach it to the doc
object. Because the second query is also asyn called, I don't know what should be returned in the map()
function, without using defer or promise, etc.