我想将其他参数传递给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);
}
});
}
如您所见,我在
i
回调中使用findOne
变量值,因为它在不同的线程中运行,所以我想将其传递给findOne
方法。我该怎么做?
最佳答案
只要您使用的是node.js 4.x或更高版本,就可以通过在let
循环中使用var
而不是for
来有效地为每次迭代创建新的作用域:
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/