Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate integer values with mongoose

I'm using mongoose and I need to define a schema like the following:

const QuestionSchema = new Schema({
    text: {
        type: String,
        required: true
    },
    number: {
        type: Number,
        required: true,
        unique: true
    }
});

I need to validate that the number field is an integer value. I have seen a couple plugins for that, e.g: mongoose-integer:

const validateInteger = require('mongoose-integer');
const QuestionSchema = new Schema({
    text: {
        type: String,
        required: true
    },
    number: {
        type: Number,
        required: true,
        unique: true,
        integer: true
    }
});
QuestionSchema.plugin(validateInteger);

But I'd prefer not using any third party libraries. Is there any other way? Thanks in advance.

like image 991
Maikel Ruiz Avatar asked Jun 08 '16 19:06

Maikel Ruiz


2 Answers

You can add a custom validator for number:

number: {
  type     : Number,
  required : true,
  unique   : true,
  validate : {
    validator : Number.isInteger,
    message   : '{VALUE} is not an integer value'
  }
}
like image 88
robertklep Avatar answered Oct 20 '22 15:10

robertklep


try using getters and setters for that:

number: {
    type: Number,
    required: true,
    unique: true,
    integer: true,
    get: v => Math.round(v),
    set: v => Math.round(v),
}
like image 2
Muslim Omar Avatar answered Oct 20 '22 14:10

Muslim Omar