将其他parameter passing给Mongoose查询
我想传递额外的参数到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
callback中使用了variables值,因为它在不同的线程中运行,所以我想把它传递给findOne
方法。
我该怎么做?
只要你使用的是node.js 4.x或者更高版本,你可以通过在for
循环中使用let
而不是var
来有效地创build一个新的作用域:
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); } }); }