简体   繁体   English

Mongoose - 无法访问对象属性?

[英]Mongoose - can't access object properties?

I am trying to access the properties of a returned MongoDB (mongoose) find. 我试图访问返回的MongoDB(mongoose)查找的属性。

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 . 但是,如果我尝试记录属性,我会得到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;
}

Any idea? 任何想法? I also tried to use JSON.parse in case it was stringified (just to make sure) but it wasn't. 我也尝试使用JSON.parse以防它被字符串化(只是为了确保),但事实并非如此。

UPDATE UPDATE

So seems like I can access the result using user._doc.email . 所以我似乎可以使用user._doc.email访问结果。 But what causes this? 但究竟是什么原因造成 I don't remember having to do this before. 我不记得以前必须这样做。

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. 如果在console.log显示文档中的字段整个文档,但是当您直接访问该字段时,则表示该模型的模式定义中缺少该字段。

So add email to the schema of User . 因此,将email添加到User的架构中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM