在mongodb for each循环查询后在SailsJS中渲染视图

我有2个集合名为“Keywords”和“Company”,我使用MongoDB聚合框架从关键字user key中的“Keywords”集合中检索相关的object._id。

当我从关键字集合中得到object._id后,我想使用object._id从公司集合中查询和编译最终的完整文档。

我在res.view()首先运行的部分停留在result []收集Company集合的所有文档之前。

我需要帮助把我的代码转换为同步方法。 请帮帮我。 以下是我所做的。

来自“关键字”集合的文档样本

{ "_id": ObjectID("52ac7130bd40d00a7beb7a29"), "keyword": "Sunshine", "object": [ { "_id": ObjectID("528443ce751fc9b805d640ad"), "type": "companyName" } ] } 

来自“公司”集合的doc样本

 { "_id": ObjectID("528443ce751fc9b805d640ad"), "name": "Sunshine Plaza", ... ... ... } 

SailsJS中的SearchController

 var keyWords = req.query.q, searchKeywords = keyWords.toLowerCase().replace(/[^\w\s]/gi, ' ').split(' '), //For example user key in "Sunshine Plaza" results = []; Keyword.native(function(err,collection){ collection.aggregate([ { $project : { '_id' : 0, 'keyword' : 1, 'object' : 1 } }, { $match : { 'keyword' : { '$in' : searchKeywords } } } , { $unwind : '$object' } , { $group : { _id : '$object._id', count : { $sum : 1 } } } , { $sort : { count: -1 } } , { $skip : 0 } , { $limit : 10 } ], function (err, docs){ docs.forEach(function (doc, i){ Company.findOne({ '_id' : doc._id },function(err,docs){ results.push(docs); }); }); }); }); res.view({ key : keyWords, results : results, layout: "layouts/search" }); 

你所错过的是,这不是阻止代码。

所以下面

 setTimeout(function() { console.log('hi'); }, 2000); console.log('bob'); 

Bob会先发生。 那hi 这是因为它不停止。

所以你应该重写你的代码的这一部分:

 function (err, docs){ docs.forEach(function (doc, i){ Company.findOne({ '_id' : doc._id },function(err,docs){ results.push(docs); }); }); }); }); res.view({ key : keyWords, results : results, layout: "layouts/search" }); 

如下所示:

 function (err, docs){ docs.forEach(function (doc, i){ Company.findOne({ '_id' : doc._id },function(err,docs){ results.push(docs); }); }, myFunction()); }); }); function myFunction() { res.view({key : keywords, results : results, layout: "layouts/search" }); }