node.js - Why does mongoose model's hasOwnProperty return false when property does exist? -


i have code :

user.findone( { 'email' : email }, function( err, user )             {                 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')); // displays here: false                 }                 if ( !user.validpass(password) )                 {                     return done(null, false, { error : "incorrect password"});                 }                 return done(null, user);             }); 

since app supports other kinds of authentication, have user model has nested object called local looks

local : { password : "users_password" } 

so during login want check whether user has provided password encountered interesting problem. test object looks this:

{ _id: 5569ac206afebed8d2d9e11e, email: 'test@example.com', phno: '1234567890', gender: 'female', dob: wed may 20 2015 05:30:00 gmt+0530 (ist), name: 'test account', __v: 0, local: { password: '$2a$07$gytktl7bsmhm8mkuh6jvc3bs/my7jz9d0kbcdukh01s' } }  

but console.log("here: " + user.hasownproperty('local')); prints here: false

where did go wrong?

it's because document object mongoose doesn't access properties directly. uses prototype chain hence hasownproperty returning false (i simplifying greatly).

you can 1 of 2 things: use toobject() convert plain object , checks work is:

var userpojo = user.toobject(); if ( !(userpojo.hasownproperty('local') && userpojo.local.hasownproperty('password')) ) {...} 

or can check values directly:

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

since neither properties can have falsy value should work testing if populated.

edit: check forgot mention use mongoose's built in get method:

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

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -