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.
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'
}
}
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),
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With