如何使用猫鼬自定义验证器

时间:2021-06-21 02:15:30

标签: javascript node.js mongodb mongoose nosql

我有一个想要验证的猫鼬模式。我想要做的是检查何时存在年龄,那么birthYear 不能为空。我已经尝试了 required 和 validate 属性,但它不起作用:(

const mongoose = require('mongoose');
const person = new mongoose.Schema({
  age: { type: Number },
  birthYear: { 
     type: String,
     required: function () {
        return this.age&& !this.age.length;
      },
      validate: [validates, 'Cannot be empty']
  },
  fullName: { type: String }
})

function validates(value) {
  return this.age && !value;
}

0 个答案:

没有答案