mongoose - 对每个数组元素执行查询

Lit*_*thy 0 javascript mongoose mongodb node.js

我有一个数组array = [key1, key2, ..., keyn]

我有一个架构:{ key : String, value : String }

我想获取一个包含与键 ( [value_associated_to_key1, ...]) 关联的值的数组。

And*_*ren 5

异步库非常适合这些情况。当您有一个数组并希望它生成另一个数组,其中各个元素之间存在某种关系时,通常使用 .map 。

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, ...]
});
Run Code Online (Sandbox Code Playgroud)

如果您有很多键,async.map 可能会使服务器过载,因为它并行调用每个请求。如果是这样,您可以使用 async.eachSeries。

更新

当然,也可以对所有值进行一次查询:

model.find({ key: { $in: array } }, function (err, result) {
  result = result.map(function (document) {
    return document.value;
  });
});
Run Code Online (Sandbox Code Playgroud)

结果现在是一个值数组。但是它不能保证它们与键的顺序相同。如果键已排序,则可以做到.find().sort({ key: 1 }).exec(callback)。否则,您必须随后将其与键数组进行比较,这可能效率低下(但仍然比查询每个键更快)。