我将函数传递给猫鼬模式中的必需验证器,但是如果我不将任何值传递给字段,则不会触发。
文档中的内容如下:
验证程序不会在未定义的值上运行。唯一的例外是必需的验证器。
参考:https://mongoosejs.com/docs/validation.html
如果我传递一个函数,该函数不适用吗?
编辑-共享代码:
我的字段定义:
var arrayAgeList = [27, 35, 135, 45, 25, 28, 24];
function even(list){
for(var i of list){
if (i % 2 === 0){
console.log(i)
}
}
}
even(arrayAgeList)
无法触发的功能:
field: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Model',
required: !isBlock,
autopopulate: true
}
答案 0 :(得分:1)
调试我发现问题出在'!'函数调用中的操作符,将代码更改为,我解决了我的问题。
required: function () { return !isBlock(this.type) }
我不明白为什么问题出在操作员身上,但是这行得通,如果有人有更好的解决方案,请在这里分享!
答案 1 :(得分:0)
我要发布与此匹配的参考代码,否则请显示您的代码。
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const cryptoRandomString = require('crypto-random-string');
const userSchema = new Schema({
firstName: {
trim: true,
type: String,
required: [true, "firstName is required!"],
validate(value) {
if (value.length < 2) {
throw new Error("firstName is invalid!");
}
}
},
lastName: {
trim: true,
type: String,
required: [true, "lastName is required!"],
validate(value) {
if (value.length < 2) {
throw new Error("lastName is invalid!");
}
}
},
email: {
unique: [true, "Email already registered"],
type: String,
required: [true, "Email is required"]
},
mobile: {
unique: [true, "Mobile Number alraedy available"],
type: String,
required: [true, "Mobile Number is required"],
validate(value) {
if (value.length !== 10) {
throw new Error("Mobile Number is invalid!");
}
}
},
password: {
type: String,
required: [true, "Password is required"],
validate(value) {
if (value.length < 6) {
throw new Error("Password must be atleast 6 characters!");
}
}
}
});