猫鼬-无法访问对象属性? [英] Mongoose - can't access object properties?

查看:63
本文介绍了猫鼬-无法访问对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问返回的MongoDB(猫鼬)查找结果的属性.

I am trying to access the properties of a returned MongoDB (mongoose) find.

如果我尝试控制台记录整个对象,则可以看到所有内容.但是,如果我尝试记录属性,则会得到undefined.对象在那里!

If I try to console log the whole object, I can see it all. But if I try to log a property, I get undefined. The object is there!

function getAll () {
    let d = q.defer();

    User.find({}, function (err, docs) {
        if (err) {
            d.reject(err);
        }

        for(let user of docs) {
            console.log(user); // This works!
            console.log(user.email); // This returns undefined!
        }

        d.resolve();
    });

    return d.promise;
}

有什么主意吗? 我还尝试使用JSON.parse以防万一它被字符串化了(只是为了确保),但事实并非如此.

Any idea? I also tried to use JSON.parse in case it was stringified (just to make sure) but it wasn't.

更新

所以看来我可以使用user._doc.email访问结果. 但是是什么原因造成的呢?我不记得以前必须这样做.

So seems like I can access the result using user._doc.email. But what causes this? I don't remember having to do this before.

推荐答案

如果在console.log整个文档中显示文档中的某个字段,但在直接访问该字段时却未显示,则表示该字段丢失了模型的架构定义.

If a field in your document shows up when you console.log the whole document, but not when you directly access that field, it means the field is missing in the model's schema definition.

因此将email添加到User的架构中.

So add email to the schema of User.

这篇关于猫鼬-无法访问对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆