4

我想在猫鼬模式验证规则中构建“minLength”和“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
    }
});

我该怎么做,这甚至可能吗?

4

4 回答 4

11

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

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

尝试 :

var validate = require('mongoose-validator').validate;

var blogSchema = new Schema({
 title: {
    type: String,
    required: true,
    validate: validate('len', 8, 32)
 }
});
于 2012-12-24T20:14:44.687 回答
6

maxlength 和 minlength 现在存在。您的代码应该如下工作。

    var mongoose = require('mongoose');
    var blogSchema = new mongoose.Schema({
        title: {
             type: String,
             required: true,
             minLength: 8,
             maxLength: 32
        }
    });
于 2016-07-22T04:24:24.667 回答
3

我有相同的功能要求。不知道,为什么 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:由于这个补丁使用了一些猫鼬的内部变量,您应该为您的模型编写单元测试,以注意补丁何时损坏。

于 2013-02-17T22:05:47.157 回答
0

最小值和最大值已更改

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

于 2019-05-29T03:13:00.203 回答