首页 > 解决方案 > mongoose Schema 中的验证

问题描述

我正在为猫鼬中的用户模式条目编写验证。我想在架构中创建两个条目(密码、googleId)中的任何一个,但不是两个条目都是必需的。我想确保用户有密码或 googleId。如何做到这一点?以下是我的架构

const UserSchema = new mongoose.Schema({
    password: {
        type: String,
        trim: true,
        required: true,
        validate: (value)=>
        {
            if(value.includes(this.uname))
            {
                throw new Error("Password must not contain username")
            }
        }
    },
    googleId: {
        type: String,
        required: true
    }
});

标签: node.jsmongoose

解决方案


您可能会做的是添加一个预验证检查,然后调用 next 或使文档无效。

const schema = new mongoose.Schema({
    password: {
        type: String,
        trim: true
    },
    googleId: {
        type: String
    }
});

schema.pre('validate', { document: true }, function(next){
    if (!this.password || !this.googleId)
        this.invalidate('passwordgoogleId'. 'One of the fields required.');
    else
        next();
});

我还没有尝试过。


推荐阅读