2016-01-20 40 views
3

我有一个猫鼬计划是这样的...猫鼬行为与数

lightbox_opacity:{type:Number, min:0, max:1}

我有2个问题...

  1. 当我尝试插入字符串“abc”,它静静地忽略这个字段的插入。 Schema中的其他字段会成功插入。我的印象是它会抛出异常。有可能这样做吗?

  2. 如果我尝试插入5,它只是允许它,它似乎最大并没有发挥作用。

我错过了什么?

回答

1

validation可以帮到你。一个例子如下。

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,如下错误

{ [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,如下错误

Mongoose save error : CastError: Cast to number failed for value "abc" at path " 
n" 
+0

谢谢,我会检查出来不久。那么,这是推荐的方法吗?正如我所说,我认为这应该是正常的。如果我错了,请纠正我。我对Mongoose比较陌生。 –

+0

@RahulSoni,是的,'验证'是推荐的方法,更多详细信息请参考我答案中的链接。 – zangw