I'm trying to make a query that will look for a specific element in an array and print out the object that the specific element resides within. I wanna do this for every element in my dataset
Here's an example of what my dataset looks like (but with around 10k more datasets. These are just the first 2 sets in the database):
/* 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"
]
}
So what I want is, first of all to find the recipes where baking powder exsists, then I wanna print ot those objects where it exists. I wanna do the same for all of the ingredients. I have tried doing following to achieve this:
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)
})
});
anyone who can explain why it's only printing out the last element in my dataset?
closureinside for loop. like this (function(i) { console.log(i); })(0)