当属性确实存在时,为什么mongoose模型的hasOwnProperty返回false?

我有这个代码:

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

由于该应用程序支持其他types的身份validation,我有一个用户模型具有嵌套对象称为本地看起来像

 local : { password : "USERS_PASSWORD" } 

所以在login时,我想检查用户是否提供了密码,但是我遇到了这个有趣的问题。 我的testing对象如下所示:

 { _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' } } 

但是console.log("here: " + User.hasOwnProperty('local')); here: false打印here: false

我哪里做错了?

这是因为你从mongoose那里得到的文档对象不能直接访问属性。 它使用原型链,因此hasOwnProperty返回false(我大大简化了这一点)。

你可以做两件事情之一:使用toObject()将其转换为一个普通的对象,然后你的检查将按原样工作:

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

或者你可以直接检查值:

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

由于这两个属性都不具有伪造价值,因此它应该适用于testing它们是否被填充。

编辑:我忘了提到的另一个检查是使用Mongoose的内置get方法 :

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

如果你只需要这些数据而不是其他的Mongoose magic,例如.save() .lean()等,那么最简单的方法就是使用.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); }); 

您也可以从MongoDB Schema中分离返回的JSON – JSONuser = JSON.parse(JSON.stringify(User)) – 然后使用JSONuser自由获取,更改或添加其任何属性。