Mongoose扩展默认验证

Mongoose expand default validation

本文关键字:验证 默认 扩展 Mongoose      更新时间:2023-09-26

我想在猫鼬模式验证规则中构建"minLength"answers"maxLength",目前的解决方案是:

var blogSchema = new Schema({
  title: { required: true, type: String }
});
blogSchema.path('title').validate(function(value) {
  if (value.length < 8 || value.length > 32) return next(new Error('length'));
});

然而,我认为这应该通过添加自定义模式规则来简化,像这样:

var blogSchema = new Schema({
    title: {
        type: String,
        required: true,
        minLength: 8,
        maxLength: 32
    }
});

我怎么能这样做,这是可能的吗?

查看库猫鼬验证器。它以与您所描述的非常相似的方式集成了节点验证器库,以便在mongoose模式中使用。

具体来说,节点验证器lenminmax方法应该提供所需的逻辑。

试题:

var validate = require('mongoose-validator').validate;
var blogSchema = new Schema({
 title: {
    type: String,
    required: true,
    validate: validate('len', 8, 32)
 }
});

maxlength和minlength现在存在。您的代码应该如下所示。

    var mongoose = require('mongoose');
    var blogSchema = new mongoose.Schema({
        title: {
             type: String,
             required: true,
             minLength: 8,
             maxLength: 32
        }
    });

我也有相同的功能要求。不知道为什么mongoose不为String类型提供最小/最大值。您可以扩展mongoose的字符串模式类型(我刚刚从数字模式类型复制了min/max函数,并将其适应为字符串-适用于我的项目)。确保在创建模式/模型之前调用补丁:

var mongoose = require('mongoose');
var SchemaString = mongoose.SchemaTypes.String;
SchemaString.prototype.min = function (value) {
  if (this.minValidator) {
    this.validators = this.validators.filter(function(v){
      return v[1] != 'min';
    });
  }
  if (value != null) {
    this.validators.push([this.minValidator = function(v) {
      if ('undefined' !== typeof v)
        return v.length >= value;
    }, 'min']);
  }
  return this;
};
SchemaString.prototype.max = function (value) {
  if (this.maxValidator) {
    this.validators = this.validators.filter(function(v){
      return v[1] != 'max';
    });
  }
  if (value != null) {
    this.validators.push([this.maxValidator = function(v) {
      if ('undefined' !== typeof v)
        return v.length <= value;
    }, 'max']);
  }
  return this;
};

PS:由于这个补丁使用了一些mongoose的内部变量,您应该为您的模型编写单元测试,以注意补丁何时被破坏。

最小值和最大值改变

var breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  },
  drink: {
    type: String,
    enum: ['Coffee', 'Tea'],
    required: function() {
      return this.bacon > 3;
    }
  }
});
https://mongoosejs.com/docs/validation.html