How to Validate Numbers in Mongoose

Updated: December 30, 2023 By: Guest Contributor Post a comment

Introduction

Mongoose is a powerful modeling tool for MongoDB that simplifies CRUD operations and includes a robust validation system. This tutorial provides insights into numerical validations, ensuring data integrity when working with numbers in Mongoose.

Basics of Number Validation

Validating numbers starts with defining a schema. Use the Number type and the validate property:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const productSchema = new Schema({
  price: {
    type: Number,
    required: true,
    validate: {
      validator: function(v) {
        return v > 0;
      },
      message: props => `${props.value} is not a valid price!`
    }
  }
});

const Product = mongoose.model('Product', productSchema);

Minimum and Maximum Validation

Control the acceptable range by specifying min and max values:

// ...other schema fields
price: {
  type: Number,
  min: [0.99, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'],
  max: 999.99
}
// ...rest of the schema

Deal with common numerical validation scenarios using inbuilt Mongoose validators and custom functions.

Ensuring Integral Numbers

price: {
  type: Number,
  validate: {
    validator: Number.isInteger,
    message: '{VALUE} is not an integer value.'
  }
}

Advanced Number Validation Techniques

Custom Asynchronous Validators

Asynchronous validators provide the ability to perform complex validations, like verifying the uniqueness of a number in the database or calling external API:

age: {
  type: Number,
  validate: {
    isAsync: true,
    validator: function(v, cb) {
      setTimeout(() => {
        const ageOver18 = v >= 18;
        cb(ageOver18);
      }, 400);
    },
    message: 'You must be at least 18 years old'
  }
}

Using External Libraries

For complex validations, integrate with libraries like Joi or validator.js:

const Joi = require('joi');

price: {
  type: Number,
  validate: {
    validator: value => Joi.number().min(0).max(999).validate(value).error === null,
    message: 'Invalid price range.'
  }
}

Final Words

Establishing validation rules can enhance your schema’s reliability and efficiency. It’s essential to perform validations at the schema level rather than later in your application.

Ensure accuracy in your validations by writing tests. Use assertion libraries like Chai and testing frameworks like Mocha to verify that your validation logic works as intended.

Validating numbers in Mongoose schemas is pivotal for maintaining data integrity. The application of minimum and maximum validation constraints, custom validators, and leveraging external libraries can vastly improve your database’s reliability and functionality.