gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:45 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com