Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - can't access object properties?

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

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;
}

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

UPDATE

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.

like image 854
Ariel Weinberger Avatar asked Apr 03 '16 03:04

Ariel Weinberger


People also ask

How do I access model properties in mongoose?

Mongoose does funky stuff when it comes to accessing model properties. Your best bet whenever you're having problems, is either to use .lean () as part of your query, or call .toObject () on the output to convert the model into a plain JS object.

What is an objectId in mongoose?

There are several other values that Mongoose can cast to ObjectIds. The key lesson is that an ObjectId is 12 arbitrary bytes. Any 12 byte buffer or 12 character string is a valid ObjectId. ObjectIds encode the local time at which they were created. That means you can usually pull the time that a document was created from its _id.

Is there a way to bypass mongoose schema?

Or you can bypass mongoose Schema and access the raw document stored in the database with docs [0]._doc.entity_id. I don't recommend this solution unless you know what you're doing. The proper solutions is adding the property to the Schema and Masadow's bypass is a functional alternative. Thank you for this answer, it helped me.

How many strings does mongoose cast to ObjectIDs?

Mongoose casts 24 char strings to ObjectIds for you based on your schema paths. There are several other values that Mongoose can cast to ObjectIds. The key lesson is that an ObjectId is 12 arbitrary bytes. Any 12 byte buffer or 12 character string is a valid ObjectId.


1 Answers

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.

So add email to the schema of User.

like image 114
JohnnyHK Avatar answered Sep 17 '22 13:09

JohnnyHK