0

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, ...]).

1 Answer 1

5

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. And don't you know whether a Mongo based solution exists (e.g. a special request) ? PS : findOne method is more adapted I think. Else replace result.value by result[0].value.
Thanks for the correction. I just realized I was too focused on how to do a query for each and didn't think about that it's possible to do one query for all of the keys at once. I updated my answer with an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.