DEV Community

Matthew Cullen
Matthew Cullen

Posted on

MERN Stack Middleware: Check if an :id is a valid Object type

This middleware was made for MERN stack projects.

When performing a GET request on a route that takes an :id to return a single object from a collect it is important to handle cases where the :id provided does not represent a valid object in our database.

GET http://localhost:5000/api/post/5f85294e21fcef22fd5b8f78

Here is some middleware we can create to help us do that.

const mongoose = require('mongoose');

// middleware to check for a valid object id in the url
const checkObjectId = (idToCheck) => (req, res, next) => {
  if (!mongoose.Types.ObjectId.isValid(req.params[idToCheck]))
    return res.status(400).json({ msg: 'Invalid ID' });
  next();
};

module.exports = checkObjectId;
Enter fullscreen mode Exit fullscreen mode

Now we can import checkObjectId and use it in any request that takes in an :id and return an object.

// IMPORTS
const express = require('express');
const router = express.Router();
// MIDDLEWARE
const checkObjectId = require('../../middleware/checkObjectId');
// MODELS
const Post = require('../../models/Post');

// @route    GET api/posts/:id
// @desc     Get post by ID
// @access   Public
router.get(
  // ROUTE
  '/:id',
  // MIDDLEWARE
  checkObjectId('id'),
  // CALLBACK
  async (req, res) => {
    try {
      const post = await Post.findById(req.params.id);

      if (!post) {
        return res.status(404).json({ msg: 'Post not found' })
      }

      res.json(post);
    } catch (err) {
      console.error(err.message);

      res.status(500).send('Server Error');
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay