我有一个像这样的猫鼬计划…
lightbox_opacity:{type:Number, min:0, max:1}
我有2个问题…
当我尝试插入字符串“ abc”时,它会静默忽略此字段的插入。模式中的其余字段将成功插入。我的印象是它将抛出异常。有可能这样做吗?
如果我尝试插入5,它只是允许它,看来min和max根本没有起作用。
我想念什么?
该验证可以帮助你。下面是一个示例。
var min = [0, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; var max = [1, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; var numberschema = new mongoose.Schema({ n: {type: Number, min: min, max: max} }); var numberschema = mongoose.model('number', numberschema, 'number'); var insertDocuments = function(db) { var a = new numberschema({ n: 5 }); console.log(a); a.validate(function(err) { if (err) console.log(err); }); a.save(function (err, ack) { if (err) { console.log('Mongoose save error : ' + err); } else { console.log('Mongoose save successfully...'); } }); };
尝试插入时5,出现以下错误
5
{ [ValidationError: Validation failed] message: 'Validation failed', name: 'ValidationError', errors: { n: { [ValidatorError: The value of path `n` (5) exceeds the limit (1).] message: 'The value of path `n` (5) exceeds the limit (1).', name: 'ValidatorError', path: 'n', type: 'max', value: 5 } } } Mongoose save error : ValidationError: The value of path `n` (5) exceeds the lim it (1).
尝试插入时abc,出现以下错误
abc
Mongoose save error : CastError: Cast to number failed for value "abc" at path " n"