【发布时间】:2019-01-18 00:23:34
【问题描述】:
我正在尝试进行查询,以查找数组中的特定元素并打印出特定元素所在的对象。我想对数据集中的每个元素都这样做
这是我的数据集的示例(但还有大约 10k 的数据集。这些只是数据库中的前 2 个数据集):
/* 1 */
{
"_id" : ObjectId("5b6b19cb1be7e54a24344bd5"),
"id" : 18009,
"ingredients" : [
"baking powder",
"eggs",
"all-purpose flour",
"raisins",
"milk",
"white sugar"
]
}
/* 2 */
{
"_id" : ObjectId("5b6b19cb1be7e54a24344bd6"),
"id" : 28583,
"ingredients" : [
"sugar",
"egg yolks",
"corn starch",
"cream of tartar",
"bananas",
"vanilla wafers",
"milk",
"vanilla extract",
"toasted pecans",
"egg whites",
"light rum"
]
}
所以我想要的是,首先找到存在发酵粉的食谱,然后我想打印那些存在的对象。我想对所有的成分做同样的事情。我已尝试执行以下操作来实现此目的:
const path = "mongodb://localhost:27017/NN_Recipes";
mongo.connect(path, function(err,db) {
console.log("Connected!")
var allIngredients;
return new Promise((resolve, reject) => {
db.collection('recipes_final').distinct("ingredients", function(err, resu) {
allIngredients = resu;
resolve();
})
}).then(data => {
for(i = 0; i < allIngredients.length; i++) {
var currentIngredient = allIngredients[i];
var individualMatrix = db.collection('recipes_final').find({
ingredients: currentIngredient
}).toArray(function(error, response) {
// console.log(currentIngredient); //This will only print the very last element in the allIngredients[i], none of the other ones.
});
//all below is just things i tried to play around with.
// console.log(i)
// console.log(individualMatrix)
// console.log(allIngredients[i])
}
// console.log(allIngredients)
})
});
谁能解释为什么它只打印出我数据集中的最后一个元素?
【问题讨论】:
-
您在 for 循环中错过了
closure。像这样 (function(i) { console.log(i); })(0)
标签: javascript arrays node.js mongodb