简体   繁体   English

Mongoose 为现有字段返回 undefined

[英]Mongoose returns undefined for an existing field

After a mongoose request I have my document doc which is the result of the query在猫鼬请求之后,我有我的文档doc ,这是查询的结果

Here is the schema used这是使用的架构

var searchSchema = new mongoose.Schema({
    original : String,
    images : [String],
    image: String
});

The model :该模型 :

var searchModel = mongoose.model('Search', searchSchema);

Code used:使用的代码:

searchModel.findOne({original : input}, function (err, doc) {
    if (err) {
        console.log(err);
    }
    if (typeof doc !== "undefined") {
        console.log(doc);
                    console.log(doc.image);
    }
});

The first console.log :第一个console.log

{ 
    _id: 531401bf714420359fd929c9,
    image: 'http://url.com/image.jpg',
    original: 'lorem ipsum dolor sit amet' 
}

The second returns undefined , but the previous one does show an existing image property, which means that it exists.第二个返回undefined ,但前一个确实显示了一个现有的image属性,这意味着它存在。

My schema doesn't have anything special so I don't understand what may be happening here..我的架构没有任何特别之处,所以我不明白这里可能发生什么..

You'll see this when you haven't added the field to your schema.当您尚未将该字段添加到架构时,您会看到这一点。

Add image to your schema and it should work:image添加到您的架构中,它应该可以工作:

image: String

This is do to the fact that the toString() method of the object returns the _doc property.这是因为对象的 toString() 方法返回 _doc 属性。 You can use: console.log(doc._doc.image);您可以使用: console.log(doc._doc.image);

我遇到了同样的错误,但是像这样访问属性doc[0].image工作正常。

Try to use the bracket notation like that:尝试使用这样的括号表示法:

doc['image']

If it works, I'm not able to explain you why, but maybe someone could shed some light on this?如果它有效,我无法向您解释原因,但也许有人可以对此有所了解?

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

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