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;
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');
}
}
);
Top comments (0)