Javascript 在Mongoose中发出多个请求
我正试图通过mongoose使用MongoDB数据库从另一个select访问不同的select,以重定向到Emberjs前端 如果上面的文本不清楚,请查看数据库的架构:Javascript 在Mongoose中发出多个请求,javascript,node.js,mongodb,ember.js,mongoose,Javascript,Node.js,Mongodb,Ember.js,Mongoose,我正试图通过mongoose使用MongoDB数据库从另一个select访问不同的select,以重定向到Emberjs前端 如果上面的文本不清楚,请查看数据库的架构: // I already get the exam content given an id Exam:{ ... collections:[{ question: Object(Id) }] ... } 在问题模式中,它是: // I want to get content
// 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
...
}
我试图让它获取集合的objects id,然后使用for来提取每个问题,并将返回的值保存到json变量中,如下所示:
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});
});
Test.findById(id,'collections',函数(err,collections){
如果(错误)
{
res.send(err);
}
var result={};//响应的json变量
//原因是找到了objectId的数量
对于(var i=0;i
有一种方法可以将请求保存到变量中,并像json一样将其返回前端?因为循环中的查询以异步方式执行,所以一旦所有操作都完成执行,您就可以发送响应 例如
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);
}
});
Test.findById(id,'collections',函数(err,collections){
如果(错误){
res.send(err);
}
var result=[];//响应的json变量
功能完成(结果){
res.json({
结果
});
}
for(var i=0,l=collections.collections.length;i
注意:未经测试,您可能需要适当地处理错误非常感谢,我看不出您可以先填充数组,然后作为响应发送它正在工作的代码,并且知道我可以在解决方案中更深入,谢谢。