【问题标题】:Mongoose - required validator not running by functionMongoose - 所需的验证器未按功能运行
【发布时间】:2020-04-24 02:36:27
【问题描述】:

我正在将一个函数传递给 mongoose 架构中所需的验证器,但如果我不向该字段传递任何值,它就不会触发。

在文档中说:

验证器不会在未定义的值上运行。唯一的例外是必需的验证器。

参考:https://mongoosejs.com/docs/validation.html

如果我传递一个函数,它不会被应用吗?

编辑 - 共享代码:

我的字段定义:

field: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Model',
      required: !isBlock,
      autopopulate: true
    }

没有触发的函数:

function isBlock() {
  return this.type === 'block'
}

【问题讨论】:

  • 请分享代码??
  • 请分享代码??
  • @MaheshBhatnagar 共享 ;)
  • 您不应该打电话给isBlock() 而不仅仅是引用它吗? !someFunction === undefined 所以当你真的想要isBlock() 的结果时,你将required 设置为false。

标签: javascript node.js mongodb validation mongoose


【解决方案1】:

调试我发现问题出在'!'函数调用中的运算符,将代码更改为我解决了我的问题。

required: function () { return !isBlock(this.type) }

【讨论】:

  • 感谢您跟进此事,这对我有帮助
【解决方案2】:

我正在发布与此匹配的参考代码,否则请显示您的代码。

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!");
            }
        }
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 2018-10-31
    • 1970-01-01
    相关资源
    最近更新 更多