当属性存在时,为什么猫鼬模型的hasOwnProperty返回false? [英] Why does mongoose model's hasOwnProperty return false when property does exist?

查看:123
本文介绍了当属性存在时,为什么猫鼬模型的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);
            });

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

Since the app supports other kinds of authentication, I have a user model that has nested object called local which looks like

local : { password : "USERS_PASSWORD" }

因此,在登录期间,我想检查用户是否提供了密码,但是遇到了这个有趣的问题. 我的测试对象如下所示:

So during login I want to check whether the user has provided a password but I encountered this interesting problem. My test object looks like 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' } } 

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

我哪里出错了?

推荐答案

这是因为从猫鼬获取的文档对象无法直接访问属性.它使用原型链,因此<一个href ="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty" rel ="noreferrer"> hasOwnProperty 返回false(我是大大简化了此步骤.)

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).

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

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.

我忘记提及的另一项检查是使用Mongoose内置的 get方法:

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

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

这篇关于当属性存在时,为什么猫鼬模型的hasOwnProperty返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆