node.js - TypeError : Cannot read property 'ref' of undefined | Express

标签 node.js mongodb express mongoose syntax-error

我正在使用Node express和mongodb。我试图能够遍历显示页面的所有相关属性。我的代码是

Desktop.find({}, function(err, allDesktop) {
            if(err){
                console.log(err);
            } else {
              console.log(allDesktop); // #1
                res.locals.desktops = allDesktop; // Set the data in locals
            }
        });
        console.log("res.locals.desktops:  ", res.locals.desktops); //#2

该代码是路由的一部分,#1 console.log注销所有正确的结果。但是console.log#2返回undefined。为什么是这样?我知道我在完全相同的路线的其他地点都设置了相似的名称,但是改为res.locals.laptops
我在这里想念什么?

最佳答案

这与Event Loop有关。简而言之,Desktop.find()将执行,但是您不知道何时完成。

那就是您的回调起作用的地方:function(err, allDesktop) {}。当Desktop.find()完成执行时,将调用回调。

因此,代码从上到下进行评估,结果res.locals.desktopsundefined。这样的事情应该可以解决您的问题:

Desktop.find({}).exec()
    .then(allDesktop => {
        res.locals.desktops = allDesktop
        return Promise.resolve()
    })
    .then(() => {
        console.log(res.locals.desktops)
    })
    .catch(err => console.error(err))
.exec()返回一个MongooseThenable,它实际上是一个Promise

关于node.js - TypeError : Cannot read property 'ref' of undefined | Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46797329/

相关文章:

python - Node.js 与 Python

mongodb - 按多个值过滤对象

mongodb - NodeJS & Mongoskin,不能做简单的更新。传入的参数必须是 12 字节或 24 十六进制字符串

node.js - Connect-mongo语法错误: unexpected token =>

node.js - 将 npm script 命令行参数传递给其中的特定脚本

Node.Js npm PDFKit 在调用 doc.end() 时崩溃

node.js - Mongoose:如何在实例方法中访问实例的属性

node.js - 为什么我在使用 selenium chromedriver 时会出现此错误?

node.js - 如何组合两个都需要监听端口的 Express 模块?

node.js - 如何检测消息的作者是否是 Discord 机器人?