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

131
Views
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 answers
Answer question

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 Report

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 Report

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 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!