node.js - 聚合中 undefined variable ( Mongoose )

标签 node.js express mongoose

我尝试在聚合中使用变量,但收到 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/

相关文章:

html - 从html中的脚本获取javascript对象

javascript - 启动服务器时找不到模块 'express-stormpath'

node.js - 显示 Mongoose 模型的多个验证错误

javascript - helpers {{#if }} 不使用expressjs 和express3-handlebars 进行渲染

javascript - 使用此错误编写 nodeJS 脚本

javascript - 尝试 POST 时无法从请求正文获取对象的值 [Node.js、MySQL]

javascript - 在我进行第二次提交后,每当我尝试获取登录页面或注册页面时,都会收到 404 错误

node.js - 使用 cloudinary npm 模块上传图像

javascript - Mongoose 似乎不支持 $max 字段更新运算符,有什么建议吗?

mongodb - 展开和匹配后的组数组