我想将附加参数传递给 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/