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

问题描述 投票:0回答:4

我有这个代码:

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: '[email protected]',
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

我哪里做错了?

node.js mongodb mongoose passport.js
4个回答
27
投票

这是因为你从 mongoose 返回的文档对象并没有直接访问属性。它使用 prototype 链,因此

hasOwnProperty
返回 false (我大大简化了这一点)。

您可以执行以下两种操作之一:使用

toObject()
将其转换为普通对象,然后您的检查将按原样工作:

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

或者您可以直接检查值:

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

由于这两个属性都不能有假值,因此如果它们已填充,则应该可以用于测试。

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

get
方法

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

1
投票

如果您只需要数据而不需要其他 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);
            });

0
投票

您还可以从 MongoDB 架构中分离返回的 JSON -

JSONuser = JSON.parse(JSON.stringify(User))
- 然后使用 JSONuser 自由获取、更改或添加其任何属性。


0
投票

我刚刚遇到了这个问题并通过使用解决了它:

"key" in obj

如何在 JavaScript 中检查对象是否有键?

© www.soinside.com 2019 - 2024. All rights reserved.