Reputation: 772
Say I want to transform array with map function and each value is looked up in mongoDB with findOne, whose criteria in turn depends on current value from the array. To put it other way, simply transform array of ids to corresponding objects fetched from DB. Like:
arr.map(function(v) {
collection.findOne({_id: v}, function(
?
});
return {newField: ?};
});
Question marks are the places that need to be filled, but I guess the whole structure needs to be changed. Hopefully I'm clear.
I'm not used to such callback thinking and cannot wrap my head around it, am I missing something obvious?
Upvotes: 0
Views: 56
Reputation: 2203
I am not an expert in MongoDB, but what you can do is set a variable before the collection
line, like this:
var return_element; var are_we_done = false;
collection.findOne({_id: v}, function(
// assign value to return_element
are_we_done = true;
)};
while (!are_we_done) {}
return {newField: <value of variable> };
Upvotes: 0
Reputation: 311865
You can use the async
library to perform an asynchronous map
, but in this case it would be easier and faster to use the $in
operator to have MongoDB get them all in one go:
collection.find({_id: {$in: arr}}).toArray(function(err, docs) {
// docs contains the docs with the _id values that were in arr
});
Upvotes: 2