I have an array array = [key1, key2, ..., keyn].
I have a schema : { key : String, value : String }.
I'd like to get an array with the values associated to keys ([value_associated_to_key1, ...]).
The async library is perfect for these situations. When you have one array and want it to result in another array where there's some relation between the respective elements, .map is normally used.
var async = require('async');
async.map(array, function (key, next) {
// Do a query for each key
model.findOne({ key: key }, function (err, result) {
// Map the value to the key
next(err, result.value);
});
},
function (err, result) {
console.log(result); // [value1, value 2, ...]
});
If you have a lot of keys, async.map might overload the server sine it calls each request in parallel. If so you could use async.eachSeries.
Update
Of course it would also be possible to do one query for all of the values:
model.find({ key: { $in: array } }, function (err, result) {
result = result.map(function (document) {
return document.value;
});
});
The result is now an array of values. However it won't guarantee that they are in the same order as the keys. If the keys are sorted one could do .find().sort({ key: 1 }).exec(callback). Otherwise you'd have to compare it to the key array afterwards, which might be inefficient (but still faster than a query for each key).
findOne method is more adapted I think. Else replace result.value by result[0].value.