8

After a mongoose request I have my document doc which is the result of the query

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:

{ 
    _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.

My schema doesn't have anything special so I don't understand what may be happening here..

nialna2
  • 2,056
  • 2
  • 25
  • 33

4 Answers4

9

You'll see this when you haven't added the field to your schema.

Add image to your schema and it should work:

image: String
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • It already is. I tried deleting all my documents, changing the field name and checking to be sure it is in the schema, then re adding everything, and while the property is there (and I can even select it in my queries) it is undefined when I try to access it, strangely – nialna2 Mar 03 '14 at 13:52
  • @Malharhak Can you update your question to include the code that defines the schema and model and performs the query that creates `doc`? – JohnnyHK Mar 03 '14 at 13:56
  • Ok never mind I have a versioning bug so my schema didn't have the right property. – nialna2 Mar 03 '14 at 17:37
  • I could kiss you (but I wont :) )! – tonyedwardspz Apr 08 '17 at 10:51
0

This is do to the fact that the toString() method of the object returns the _doc property. You can use: console.log(doc._doc.image);

Aryeh Armon
  • 2,137
  • 2
  • 22
  • 37
0

I had the same error, but accessing the property like this doc[0].image works fine.

Justin Herrera
  • 526
  • 4
  • 11
-1

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?

inwpitrust
  • 561
  • 3
  • 7
  • 20