NodeJS mongoose模式中的验证

xghobddn  于 2023-03-17  发布在  Node.js
关注(0)|答案(3)|浏览(172)

我正在为mongoose中的用户模式条目编写验证。我希望在模式中设置两个条目(密码、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
    }
});
lymnna71

lymnna711#

您可以使用自定义验证器:

const UserSchema = new mongoose.Schema({
    password: {
        type: String,
        trim: true,
        required: true,
        validate: {
            validator: checkCredentials,
            message: props => `${props.value} is not a valid phone number!`
        },
    },
    googleId: {
        type: String,
        required: true
    }
});

function checkCredentials(value) {
   if (!this.password || !this.googleId) {
       return false;
   }
   return true; 
}

或者使用pre验证中间件

UserSchema.pre('validate', function(next) {
    if (!this.password || !this.googleId) {
        next(new Error('You should provide a google id or a password'));
    } else {
        next();
    }
});
xdyibdwo

xdyibdwo2#

Mongoose模式提供了一个prevalidate中间件,用于验证文档,并在验证之前对文档进行必要的修改。

import mongoose, { ValidationError } from "mongoose";
const UserSchema = new mongoose.Schema({
    password: {
        type: String,
        trim: true,
    googleId: {
        type: String,
    }
});

// This is a middleware
UserSchema.pre('validate', (next) => {
  if (!this.password && !this.googleId) {
    // if both are not available then throw the error
    const err = new ValidationError(this);
    err.errors.password = new ValidationError.ValidatorError({
      message: 'At least one of password or googleId must be present.',
      path: 'password',
      value: this.password
    });
    next(err);
  }
  else { 
    next();
  }
});
sqougxex

sqougxex3#

您可能要做的是添加一个预验证检查,然后调用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();
});

我还没试过呢。

相关问题