我尝试在聚合中使用变量,但收到 undefined variable 消息:
var rows = [{name:'hi1'}, {name:'hi2'}];
for (var i = rows.length - 1; i >= 0; i--) {
var query = Collection.aggregate([{ $match: {name: rows[i].name}}]);
query.exec((err, docs)=>{
console.log(rows[i].name)
})
错误
TypeError: Cannot read property 'name' of undefined
关于正确的顺序有什么建议吗?
谢谢!
最佳答案
您遇到了经典的 js 关闭错误。
发生这种情况是因为 var
不安全并且是在 for
循环之外“声明”的。
你可以自己查一下:
for(var i = 0; i<10; i++){
console.log(i); // prints i from 0 to 9
}
console.log(i); // prints 10
在异步操作的上下文中,实际值 if i
是在这些操作结束时从内存中获取的。当查询完成执行时 - 循环结束,因此 i
的实际值等于 -1
。
要避免这种行为,请使用 es6 let
而不是 var
。
您可以在this videio获取更多信息.
关于node.js - 聚合中 undefined variable ( Mongoose ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51852866/