【问题标题】:Cannot read property 'value' of undefined - mongoose 5.6.0无法读取未定义的属性“值”-猫鼬 5.6.0
【发布时间】:2019-06-15 03:00:37
【问题描述】:

当使用 mongoose 的 findOne 函数并按特定字段搜索时,我遇到了一个奇怪的错误。我正在使用 mongoose 5.6.0 和 mongoDB 3.6.9。

我不知道是什么问题,请帮忙!

来电:

User.findOne({googleId:googleId})
    .select('-password')
    .exec()
    .then(user => {
        if(user)
        {
            const googleUser = user;
            return done(null, googleUser);
        }
        else
        {
            const newUser = new User({
                _id: new mongoose.Types.ObjectId(),
                method: "Google",
                email: profile.emails[0].value,
                googleId: googleId,
                role: "User"
            });

            newUser.save()
            .then(saveduser => {
                const googleUser = saveduser;
                return done(null, googleUser);
            })
            .catch(error => {
                log.error("Error saving Google ID: " + googleId + " => " + error.message);
                return done(error, false)
            })
        }
    })
    .catch(error => {
        log.error("Error looking up Google ID: " + googleId + " => " + error.message);
        return done(error, false)
    })

这是用户架构:

/*
==============================================
User Model
==============================================
*/

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    email: { 
        type: String,         
        unique: true,
    },
    password: { 
        type: String,
        required: function() {
            return this.method === "Local";
        }
    },
    role: {
        type: String,
        enum: ["Developer", "Admin", "Moderator", "User"],
        required: true
    },
    enabled: {
        type: Boolean,
        required: true,
        default: true
    },
    method: {
        type: String,
        enum: ["Local", "Google", "Facebook"],
        default: "Local"
    },
    googleId: {
        type: String,
        default: ''
    },
    facebookId: {
        type: String,
        default: ''
    }
},
{
    timestamps: true
});

module.exports = mongoose.model('User', userSchema);

这是错误:

[2019-06-14T22:47:16.055] 无法读取未定义的属性“值”

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    您有一个profile,它要么没有emails 数组,要么数组为空,因为profile.emails[0].value 是您得到错误的地方。

    只需检查以确保您拥有 emails 数组并且有第一个元素。

    你可以这样做:

    email: profile && profile.emails && profile.emails.length && profile.emails[0].value
    

    或者甚至更好地将该电子邮件传递到此部分并事先对其进行清理。

    【讨论】:

    • 哇。真是个陷阱。我在那一个上完全错误的兔子洞。干杯:D
    • 刚刚确认。缺少我的谷歌身份验证的范围。拉了一个较旧的提交,我似乎已经删除了它。再次感谢!
    猜你喜欢
    • 2019-12-11
    • 2016-11-12
    • 1970-01-01
    • 2021-09-06
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    相关资源
    最近更新 更多