Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

303
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda