2012-12-24 64 views
2

我想在貓鼬模式驗證規則,以打造「的minLength」和「最大長度」,目前的解決方案是:貓鼬擴大默認的驗證

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

我該怎麼做,這甚至有可能嗎?

回答

10

查看圖書館mongoose-validator。它以非常相似的方式集成了用於貓鼬模式的節點驗證器庫。

具體地說,node-validatorlen個分鐘最大方法應提供您所需要的邏輯。

嘗試:

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

var blogSchema = new Schema({ 
title: { 
    type: String, 
    required: true, 
    validate: validate('len', 8, 32) 
} 
}); 
3

我有同樣的功能要求。不知道,爲什麼貓鼬不提供String類型的最小/最大值。您可以擴展貓鼬的字符串模式類型(我剛剛從數字模式類型複製了最小/最大值函數,並將其調整爲字符串 - 對我的項目工作正常)。請確保您創建模式/模型前致電補丁:

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:由於這個補丁使用貓鼬內部的一些變量,你應該寫單元測試你的模型,當斑塊破裂的通知。

3

現在存在maxlength和minlength。你的代碼應該如下工作。

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