Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
899 views
in Technique[技术] by (71.8m points)

node.js - Mongoose behaviour around Min and Max with Number

I have a Mongoose scheme like so...

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

I have 2 issues...

  1. 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?

  2. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...