javascript - MongoDB .findOne 范围

标签 javascript node.js mongodb mongoose

我对 var 范围有疑问。

var max;
    ClassModel.findOne({ class: '1a' }, function (err, class1a) {
        if (err) return handleError(err);
        max = class1a.members;
        console.log(max);
    });
console.log(max);

为什么第一个日志记录正确的值,但第二个日志未定义?

最佳答案

第二个console.log显示undefined,因为mongoose的findOne是异步的。当您显示第一个 console.log 时,结果已被处理,而第二个则没有。

Mongoose async operations, like .save() and queries, return Promises/A+ conformant promises. This means that you can do things like MyModel.findOne({}).then() and yield MyModel.findOne({}).exec() (if you're using co).

您可以做的一件事是检查它何时完成,例如..

 var max;
 var query = ClassModel.findOne({ class: '1a' }, function (err, class1a) {
     if (err) return handleError(err);
     return class1a.members;
});

query.then(function(data) {
    console.log(data); // will show class1a.members value
});

Docs

关于javascript - MongoDB .findOne 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40347458/

相关文章:

javascript - JSX 文件类型的 Nextjs 配置

mongodb - 使用start-stop-daemon时无法多次启动mongodb?

javascript - 指令在删除后获取其他指令的数据

node.js - 如何从node.js@heroku上传图像到cloudinary?

c# - Jquery类及其功能

javascript - Nunjucks nl2br 不存在?

arrays - 如何更新 MongoDB 中的多级嵌套数组?

html - 如何在 HTML 中显示 ImageGridFSProxy?

javascript - 奇怪的 session 存储行为

javascript - CSS 转换在 IE-11 中不起作用