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

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

我哪里做错了?

推荐答案

这是因为您从 mongoose 返回的文档对象没有直接访问属性.它使用 prototype 链,因此 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.

我忘记提及的另一个检查是使用猫鼬内置的 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天全站免登陆