Node.js: validate a MongoDB ID

In Node.js we can validate a MongoDB's ID.

We install first the required module:


npm install validator --save

Then we can validate an ID, for example in an Express route:


'use strict';

const app = require('express')();
const validator = require('validator');

app.get('/api/items/:id', (req, res) => {
   let id = req.params.id;
   if(!validator.isMongoId(id)) {
       // Error
   } else {
       //...
   }
});

Prev Articles Next