在Mongoose中发出多个请求

我试图从MongoDB数据库与mongoose的其他select到另一个selectredirect到Emberjs前端。

如果上面的文本不清楚,请查看数据库的模式:

// I already get the exam content given an id Exam:{ ... collections:[{ question: Object(Id) }] ... } 

在问题模式中是:

 // I want to get content of this giving an id question:{ ... questions: String, // I want to get this given an Id exam value: Number // and this ... } 

我试图让它获取集合的对象id,然后做一个提取每个问题,并将返回的值保存到一个jsonvariables,如下所示:

 Test.findById(id, 'collections', function(err, collections){ if(err) { res.send(err); } var result ={}; //json variable for the response // the for it's with the number of objectId's that had been found for(var i = 0; i < collections.collections.length; i++) { // Send the request's to the database QuestionGroup.findById(collections.collections[i].id, 'questions').exec(function(err, questiongroup) { if(err) { res.send(err); } // save the results in the json result.questiongroup = questiongroup; // prints questions console.log(result); }); // it return's {} console.log(result); } // also return {} console.log(result); res.json({result: result}); }); 

有没有办法将请求保存到一个variables,并返回它像一个JSON到前端?

由于循环中的查询以asynchronous方式执行,所以一旦执行完成,就会发送响应。

例如。

 Test.findById(id, 'collections', function(err, collections) { if (err) { res.send(err); } var result = []; //json variable for the response function done(result) { res.json({ result }); } for (var i = 0, l = collections.collections.length; i < l; i++) { // i need needs to be in private scope (function(i) { QuestionGroup.findById(collections.collections[i].id, 'questions').exec(function(err, questiongroup) { if (err) { res.send(err); } // save the results in the json result.push(questiongroup); if (l === i + 1) { done(result); } }); })(i); } }); 

注:未经testing,您可能需要适当地处理错误