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

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

我有这个代码:

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

由于该应用支持其他类型的身份验证,我有一个用户模型,其中包含名为 local 的嵌套对象,看起来像

local : { password : "USERS_PASSWORD" }

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

{ _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: 'a$gytktl7BsmhM8mkuh6JVc3Bs/my7Jz9D0KBcDuKh01S' } } 

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

我哪里错了?

这是因为您从 mongoose 返回的文档对象没有直接访问属性。它使用 prototype chain hence hasOwnProperty 返回 false(我大大简化了这个)。

您可以执行以下两项操作之一:使用 toObject() 将其转换为普通对象,然后您的检查将按原样工作:

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

或者您可以直接检查值:

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

由于两个属性都不能有假值,因此应该可以测试它们是否已填充。

编辑:我忘记提及的另一项检查是使用 Mongoose 的内置 get method:

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

如果您只需要数据而不需要其他 Mongoose 魔法,例如 .save().remove() 等,那么最简单的方法是使用 .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 架构中分离返回的 JSON - JSONuser = JSON.parse(JSON.stringify(User)) - 然后使用 JSONuser 自由获取、更改或添加其任何属性.