node.js - 将附加参数传递给 Mongoose 查询

标签 node.js mongodb

我想将附加参数传递给 Mongoose findOne 查询。

这是我的伪代码:

for (var i = 0; i < 5; i++) {
    SomeCollection.findOne({name: 'xxx' + i}, function (err, document) {
        if (document) {
            console.log('aaa' + i + document.somefield);  
        }
    });
}  

如您所见,我在 findOne 回调中使用 i 变量值,因为它在不同的线程中运行,我想将其传递给 findOne 方法。

我该怎么做?

最佳答案

只要您使用 node.js 4.x 或更高版本,您就可以使用 let 在每次迭代中有效地创建一个新范围。而不是 for 循环中的 var:

for (let i = 0; i < 5; i++) {
    SomeCollection.findOne({name: 'xxx' + i}, function (err, document) {
        if (document) {
            // i will have the same value from the time of the findOne call
            console.log('aaa' + i + document.somefield);  
        }
    });
}

关于node.js - 将附加参数传递给 Mongoose 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38031726/

相关文章:

mongodb - 查询Mongo中是否有空对象

javascript - 从 Node js中的缓冲区检测文件类型?

javascript - async.waterfall 方法中未定义回调

node.js - 监听附加端口 Microsoft Azure Nodejs

xml - Spring 数据 mongodb : adding credentials for MongoDb access

javascript - 如何使用express和mongoose中的参数使聚合函数动态化

node.js - Mongoose,如何在现有 JSON 文档中将元素附加到数组

javascript - 如何访问函数中的命名参数?

node.js - Node 控制台在哪里?

ruby - 使用 Sinatra 和 MongoDB- 关闭连接?