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"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…