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: 'refo@mailinator.com',
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: 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)
Ok, so I found the issue, there are only 23 characters in my object Id one is missing from start. but still why there is id field missing that mongoose add and why there _id is new ObjectId("618fb03e37876d1f0bccb945") instead of simply "618fb03e37876d1f0bccb945" when I'm logging
I was facing the same problem, and this is how I solved to get the data for the Id I'm looking for.
const ObjectId = require('mongodb').ObjectId;
const id = '61929f3efc232d63cd9dcb6b';
user.findOne({ _id: ObjectId(id) })
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
This is the data that I have for users information
The Output:
{
_id: new ObjectId("61929f3efc232d63cd9dcb6b"),
name: 'Ibrahem',
email: 'I-A-H@hotmail.com',
age: 24,
createdAt: 2021-11-15T17:56:14.089Z,
updatedAt: 2021-11-15T17:56:14.089Z,
__v: 0
}
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');
try:
await User.findOne({ _id: mongoose.Types.ObjectId(id) });