我正在使用 nodejs+express+mongoose。假设我有 2 个模式和模型:“水果”和“蔬菜”。
假设我有以下内容:
var testlist = ["Tomato", "Carrot", "Orange"];
var convertedList = [];
// Assume res is the "response" object in express
我希望能够分别根据“水果”和“蔬菜”集合检查数组中的每个项目,并将它们插入到转换后的列表中,其中番茄、胡萝卜和西兰花被各自的文档替换。
下面我有一些我认为的伪代码,但不知道该怎么做。
for(var i = 0; i < testlist.length; i++) {
var fruitfind = Fruit.find({"name":testlist[i]});
var vegfind = Vegetables.find({"name":testlist[i]});
// If fruit only
if(fruitfind) {
convertedList.push(fruitfindresults);
}
// If vegetable only
else if(vegfind) {
convertedList.push(vegfindresults);
}
// If identified as a fruit and a vegetable (assume tomato is a doc listed under both fruit and vegetable collections)
else if (fruitfind && vegfind) {
convertedList.push(vegfindresults);
}
}
// Converted List should now contain the appropriate docs found.
res.send(convertedList) // Always appears to return empty array... how to deal with waiting for all the callbacks to finish for the fruitfind and vegfinds?
做这个的最好方式是什么?或者这甚至可能吗?