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

132
Visualizações
user._id does not match user._id in mongodb

so I have a problem that my user._id matches "61a242dffecd0e0f7b3e36b8" but it always picks the else statement am I doing something wrong?

const user = await User.findById(req.params.id);
if ("61a242dffecd0e0f7b3e36b8" === user._id) {
  res.send("hello");
} else {
  return res.send({ message: "access denied" });
}

also, the string matches the user._id and when I console.log(user._id) it returns this:

new ObjectId("61a242dffecd0e0f7b3e36b8")

also, this does match with the user._id but again it does not pick the if statement

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

That's because you're using strict equality === and the types are not equal. The returned user._id is of type mongoose.Types.ObjectId (or something similar). The mongoose.Types.ObjectId does have a toString() method though, so if you console.log it, it appears to be a string. Try this:

const user = await User.findById(req.params.id);
if ("61a242dffecd0e0f7b3e36b8" === user._id.toString()) {
  res.send("hello");
} else {
  return res.send({ message: "access denied" });
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You could wrap the ID you want to check with ObjectId before the check.

Here is a snippet that would work

const { ObjectId } = require('mongoose').Types

const user = await User.findById(req.params.id);

if (ObjectId("61a242dffecd0e0f7b3e36b8") === user._id) {
  res.send("hello");
} else {
  return res.send({ message: "access denied" });
}
about 4 years ago · Juan Pablo Isaza Relatório

0

const user = await User.findById(req.params.id);
if(user == null) throw new Error("User Not Found");
if (user._id.toString() === "61a242dffecd0e0f7b3e36b8") {
  res.send("hello");
} else {
  return res.send({ message: "access denied" });
}
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