我有这个密码:

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

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

我哪里出错了?

推荐答案

这是因为从mongoose返回的文档对象不能直接访问属性.它使用prototype链,因此hasOwnProperty返回false(我将大大简化).

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

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

或者您可以直接判断值:

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

因为这两个属性都不能有falsy值,所以如果填充了它们,就应该对它们进行测试.

编辑:我忘了提到的另一个判断是使用Mongoose的内置get method:

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

Mongodb相关问答推荐

MongoDB v4.4聚合的$getfield替代方案

筛选出嵌套数组中的记录Mongo DB聚合

在MongoDB中获取所有帖子时如何获取相关用户信息

如何从集合中移除所有匹配的数组项?

Mongodb 按数组元素聚合组

将 MongoDB 转移到另一台服务器?

为什么使用整数作为 pymongo 的键不起作用?

使用 mgo 从 golang 中的 Mongodb 中 Select 列

使用 AngularJs 和 MongoDB/Mongoose

Meteor 如何接收对 MongoDB 查询结果的更新?

如何在 $lookup Mongodb 的 LocalField 中将字符串转换为 objectId

什么是 mongodb 中的admin数据库?

mongodb-nodejs-driver,DeprecationWarning:collection.count 已弃用

如何使用 angular.js 推送通知?

MongoDB 数据库,相当于 SELECT column1, column2 FROM tbl

MongoDB如何判断是否存在

获取 mongodb 中所有唯一标签的列表

无法将 Mongoose 连接到 Atlas

PyMongo 中的警告消息:count is deprecated

在 MongoDB 中比较日期(moment.js)