Sling Academy
Home/Node.js/How to Validate Numbers in Mongoose

How to Validate Numbers in Mongoose

Last updated: December 30, 2023

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.

Next Article: Understanding the Map schema type in Mongoose

Previous Article: Virtuals in Mongoose: Explained with Examples

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates