javascript - Node.js:回调值相互依赖

标签 javascript node.js mongodb

假设我想使用map函数转换数组,并且使用findOne在mongoDB中查找每个值,其标准又取决于数组中的当前值。换句话说,只需将 ids 数组转换为从数据库中获取的相应对象即可。喜欢:

arr.map(function(v) {
            collection.findOne({_id: v}, function(
                              ?
            });

            return {newField: ?};
});

问号是需要填写的地方,但我猜整个结构需要改变。希望我说得清楚。

我不习惯这种回调思维,无法理解它,我是否错过了一些明显的东西?

最佳答案

您可以使用async执行异步的库 map ,但在这种情况下,使用 $in 会更容易、更快。操作符让 MongoDB 一次性获取所有这些:

collection.find({_id: {$in: arr}}).toArray(function(err, docs) {
    // docs contains the docs with the _id values that were in arr
});

关于javascript - Node.js:回调值相互依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27756543/

相关文章:

javascript - Promise在这种情况下如何实现?

javascript - 如何通过 Github API 将内容上传到隐藏文件夹名称?

node.js - 如何在 mongoDB 中将 $subtract 与文档数组一起使用

java - 如何使用 Java 中的 Morphia 和 Play 框架从实体中检索特定字段

javascript - 带回调的 Angular EventEmitter

javascript - 下划线 : what's meaning of 'context' in the source code comment

javascript - mqtt messages.client javascript nodejs

java - Spring 数据休息: Nested objects not being stored in separate Mongo Repository

javascript - 在 React 应用程序中映射对象数组时出错

javascript - AngularJS 路由功能不起作用