3
我有一個貓鼬計劃是這樣的...貓鼬行爲與數
lightbox_opacity:{type:Number, min:0, max:1}
我有2個問題...
當我嘗試插入字符串「abc」,它靜靜地忽略這個字段的插入。 Schema中的其他字段會成功插入。我的印象是它會拋出異常。有可能這樣做嗎?
如果我嘗試插入5,它只是允許它,它似乎最大並沒有發揮作用。
我錯過了什麼?
我有一個貓鼬計劃是這樣的...貓鼬行爲與數
lightbox_opacity:{type:Number, min:0, max:1}
我有2個問題...
當我嘗試插入字符串「abc」,它靜靜地忽略這個字段的插入。 Schema中的其他字段會成功插入。我的印象是它會拋出異常。有可能這樣做嗎?
如果我嘗試插入5,它只是允許它,它似乎最大並沒有發揮作用。
我錯過了什麼?
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"
謝謝,我會檢查出來不久。那麼,這是推薦的方法嗎?正如我所說,我認爲這應該是正常的。如果我錯了,請糾正我。我對Mongoose比較陌生。 –
@RahulSoni,是的,'驗證'是推薦的方法,更多詳細信息請參考我答案中的鏈接。 – zangw