Reputation: 4968
I have a Mongoose scheme like so...
lightbox_opacity:{type:Number, min:0, max:1}
I have 2 issues...
When I try to insert a string "abc", it quietly ignores this fields insertion. Rest of the fields in the Schema get inserted successfully. I was under the impression that it will throw an exception. Is it possible to do that?
If I try to insert 5, it simply allows it and it appears that min & max didn't come into play at all.
What am I missing?
Upvotes: 8
Views: 15763
Reputation: 48496
The validation could help you. One example as below.
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...');
}
});
};
When try to insert 5
, error as below
{ [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).
When try to insert abc
, error as below
Mongoose save error : CastError: Cast to number failed for value "abc" at path "
n"
Upvotes: 8