Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set minimum value great then 0 in mongoose schema?

I think that it was easy question, but I am puzzled. How Can I add minimum value to mongoose > 0?

var customer = new Schema({
  cash: {
    type: Number,
    minimum: 0
  }
});

this code allow 0 value, but I want to do > 0

I know, I can do this

var customer = new Schema({
      cash: {
        type: Number,
        minimum: 0
      },
      validate: {
        validator: function(value) {
          return value > 0;
        },
        message: 'cash need to be > 0'
      },
});

*cash is float, and can be very small

But it's too long, Is there an easier way?

like image 894
Jackson Avatar asked Jul 11 '17 10:07

Jackson


1 Answers

You ca specify the min while defining the schema.

    var breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  },
  drink: {
    type: String,
    enum: ['Coffee', 'Tea'],
    required: function() {
      return this.bacon > 3;
    }
  }
});
var Breakfast = db.model('Breakfast', breakfastSchema);

`

var badBreakfast = new Breakfast({
  eggs: 2,
  bacon: 0,
  drink: 'Milk'
});
var error = badBreakfast.validateSync();
assert.equal(error.errors['eggs'].message,
  'Too few eggs');
assert.ok(!error.errors['bacon']);
assert.equal(error.errors['drink'].message,
  '`Milk` is not a valid enum value for path `drink`.');

badBreakfast.bacon = 5;
badBreakfast.drink = null;

error = badBreakfast.validateSync();
assert.equal(error.errors['drink'].message, 'Path `drink` is required.');

badBreakfast.bacon = null;
error = badBreakfast.validateSync();
assert.equal(error.errors['bacon'].message, 'Why no bacon?');
like image 92
Akash Kukkar Avatar answered Nov 14 '22 23:11

Akash Kukkar