Why does mongoose model's hasOwnProperty return false when property does exist? Why does mongoose model's hasOwnProperty return false when property does exist? mongoose mongoose

Why does mongoose model's hasOwnProperty return false when property does exist?


It's because the document object you get back from mongoose doesn't access the properties directly. It uses the prototype chain hence hasOwnProperty returning false (I am simplifying this greatly).

You can do one of two things: use toObject() to convert it to a plain object and then your checks will work as is:

var userPOJO = User.toObject();if ( !(userPOJO.hasOwnProperty('local') && userPOJO.local.hasOwnProperty('password')) ) {...}

OR you can just check for values directly:

if ( !(User.local && User.local.password) ) {...}

Since neither properties can have a falsy value it should work for testing if they are populated.

EDIT: Another check I forgot to mention is to use Mongoose's built in get method:

if (!User.get('local.password')) {...}


If you only need the data and not the other Mongoose magic such as .save(), .remove() etc then the most simple way would be to use .lean():

user.findOne( { 'email' : email }, function( err, User ).lean()            {                if ( err )                {                    return done(err);                }                if ( !User )                {                    return done(null, false, { error : "User not found"});                }                if ( !User.hasOwnProperty('local') || !User.local.hasOwnProperty('password') )                {                    console.log("here: " + User.hasOwnProperty('local')); // Should now be "here: true"                }                if ( !User.validPass(password) )                {                    return done(null, false, { error : "Incorrect Password"});                }                return done(null, User);            });


You can also detach the returned JSON from MongoDB Schema - JSONuser = JSON.parse(JSON.stringify(User)) - and then use JSONuser freely getting, changing or adding, any of its properties.