Home > Net >  Why findOne({ id }) is not working properly in mongoose 6.012
Why findOne({ id }) is not working properly in mongoose 6.012

Time:11-15

I am using mongoose to find one user by its id but it is not working correctly. I tried several different approaches but only got the wrong results or errors.

Here is my code.

const { id } = req.params;
const user = await User.findOne({ id });
console.log(id);
console.log(user);
return res.redirect("back");

I tried following approaches

1 - await User.findOne({ id }); returning first user no matter what is id.

target id: a8fc083f3f55494fa2cadf9
{
  _id: new ObjectId("618fb03e37876d1f0bccb945"),
  name: 'bohetefyhy',
  email: '[email protected]',
  dataRealm: new ObjectId("618fb0119eefb1308fe65610"),
  role: 'user',
  createdAt: 2021-11-13T12:31:58.846Z,
  updatedAt: 2021-11-15T08:03:34.422Z,
  __v: 0
}

2 - await User.findOne({ id }); returning same result as above (1).

3 - await User.findOne({ _id: id }); giving error.

CastError: Cast to ObjectId failed for value "a8fc083f3f55494fa2cadf9" (type string) at path "_id" for model "User"
at model.Query.exec (C:\Users\khan\Documents\Projects\030FL014_Windshield\app\node_modules\mongoose\lib\query.js:4545:21)
at model.Query.Query.then (C:\Users\khan\Documents\Projects\030FL014_Windshield\app\node_modules\mongoose\lib\query.js:4644:15)
at processTicksAndRejections (internal/process/task_queues.js:97:5)

I also noticed that in the result there is a missing id field that mongoose adds. And for _id value is new ObjectId("618fb03e37876d1f0bccb945") instade of simply "618fb03e37876d1f0bccb945"

I am using

"mongoose": "^6.0.12",

MongoDB 5.0.3 2008R2Plus SSL (64 bit)

CodePudding user response:

Mongoose's findById method casts the id parameter to the type of the model's _id field so that it can properly query for the matching doc.

Try also checking

if (id.match(/^[0-9a-fA-F]{24}$/)) { // Yes, it's a valid ObjectId, proceed with findById call. }

OR

var mongoose = require('mongoose'); mongoose.Types.ObjectId.isValid('your id here');

CodePudding user response:

Try doing so if your search by id :

const user = await User.findById(id);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related