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.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With