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

3

7

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?

Parthenia answered 11/7, 2017 at 10:16 Comment(4)
You already discounted something like minimum: 0.00000001, but for Number types, min and max are the only two options, and they work the way they work ("less/greater than, or equal"). Anything else, you need to implement yourself.Ivetteivetts
If you take this information from official docs, you can create answer with text from this commentary, and I will approve itParthenia
you shouldn't represent monetary values as (small) floats to begin with, due to rounding errors.Ivetteivetts
it's example value, but in our project we need to use floatParthenia
D
6

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?');
Delphiadelphic answered 14/11, 2019 at 11:58 Comment(0)
C
1

http://mongoosejs.com/docs/api.html#schema-number-js

Try this:

var customer = new Schema({
  cash: {
    type: Number,
    min: 1
  }
});

I assume you are using mongoose.js?

Cottonweed answered 11/7, 2017 at 12:10 Comment(1)
cash is float, and can be very smallParthenia

© 2022 - 2024 — McMap. All rights reserved.