我有一个像这样的 Mongoose 方案......
lightbox_opacity:{type:Number, min:0, max:1}
我有两个问题...
当我尝试插入一个字符串“abc”时,它悄悄地忽略了这个字段插入。架构中的其余字段已成功插入。我的印象是它会抛出异常。有可能吗?
如果我尝试插入 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"
关于node.js - Mongoose 围绕 Min 和 Max 与 Number 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34892143/