Home > Software design >  user._id does not match user._id in mongodb
user._id does not match user._id in mongodb

Time:11-28

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

CodePudding user response:

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" });
}

CodePudding user response:

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" });
}

CodePudding user response:

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" });
}
  • Related