Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
How to check for a valid Object Id in mongoose?

I have a route that returns a particular story from an object Id. When i try testing it, it gives me some errors. The code inside if block is not executing somehow.

router.get("/:id",async (req,res) => {
  try{
    if (!isValidObjectId(req.params.userId)) {
    res.status(401).json({
      message: "Invalid object id",
      success: false
    })
    throw new Error("Invalid object id")
  }
    let story = await Story.findById(req.params.id)
    .populate('user')
    .lean()

    if (!story) {
       return res.status(404).json({
        message: "Story not found",
        success: false
      })
    }
const text = convert(story.body, {
  wordwrap: null
});
    res.render('stories/show',{
      story,
      title: `${story.title} Storybooks`,
      desc: `${text}`
    })
  }
  catch(err) {
    console.error(err)
  }
})

I don't want to execute the query if the id is not valid say /stories/blabla

How can i do that?

Your response is appreciated.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

For those of you struggling with the problem here is a time saver:

First we us the method isValid on mongoose.Types.ObjectId then as a 2nd check we create an actual object id an compare it as a string.

Here's how you would import and use it:

const mongoose = require('mongoose');
const {Types: {ObjectId}} = mongoose;

const validateObjectId = (id) => ObjectId.isValid(id) && (new ObjectId(id)).toString() === id; //true or false

As to answering my own question:

 
const mongoose = require('mongoose');
const {Types: {ObjectId}} = mongoose;

const validateObjectId = (id) => ObjectId.isValid(id) && (new 
ObjectId(id)).toString() === id; //true or false

// @desc Show a single story
// @route GET /stories/:id

router.get("/:id",async (req,res) => {
  try{
    if (!validateObjectId(req.params.id)) {
      throw Error("Invalid object Id")
    }
    let story = await Story.findById(req.params.id)
    .populate('user')
    .lean()

    if (!story) {
       return res.status(404).json({
        message: "Story not found",
        success: false
      })
    }
const text = convert(story.body, {
  wordwrap: null
});
    res.render('stories/show',{
      story,
      title: `${story.title} Storybooks`,
      desc: `${text}`
    })
  }
  catch(err) {
    console.error(err)
  }
})

EDIT:

I used req.params.userId instead of req.params.id so the above method is totally fine.

But just learnt a new way of doing it.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!