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.
MongoDB is a non-relational database and doesn't support joins.
For this needs please check data models documentation .
Also look at practice of using MapReduce
: http://cookbook.mongodb.org/patterns/pivot/
Node.js behaviors is asynchronous in which callbacks will be executed after getting result set . In your code you are doing multiple call to mongodb , which can be avoided by using $in construct . Doing multiple mongo call in loop is bad design where you can't ensure when to return or beak loop , because you don't know when call back will be called . To avoid this just collect all doc _id and do one mongo call using $in construct . This will avoid the confusion of when to send response .Something like :
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 docId = _(docs).map(
function (doc) {
return parseInt(doc._id);
});
markModel.findOne({
question_id: {
$in: docId
},
user_id: user_id
},
function (err, markDoc) {
if (markDoc)
doc.mark = markDoc;
res.send(result); // send result
});
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.