Reputation: 93
I need to find a user by his mongodb collection's _id
,
in need the search to be done using the first 5 characters in the user id
example with 5e9cca
i can find the collection id 5e9cca24beabb96a4caedc35
var id = req.body.id
User.findById({ _id : { $regex: '^id', $options: 'i' } },
(err, user) => {
if (err) {
console.log(err);
res.status(400)
}
with this code i got this error :
MongooseError [CastError]: Cast to ObjectId failed for value "{ _id: { '$regex': '^id', '$options': 'i' } }" at path "_id" for model "User"
PS : The search using the hole id is working
Upvotes: 2
Views: 1276
Reputation: 17915
Mongoose's .findById() will take in a string & internally it will convert string into ObjectId()
. So .findById()
is kind of a wrapper to MongoDB's native function .findOne()
and all it can take is a string. Additionally you can not do regex search on _id
field as it's not of type string
. If at all you need to do this, try below :
On MongoDB version >4.0 :
db.collection.aggregate([
/** Create a field of type 'string' from `_id`*/
{ $addFields: { convertedId: { $toString: "$_id" } } },
/** Regex search against it */
{
$match: {
convertedId: {
$regex: "^1a934e",
$options: "i"
}
}
},
/** Remove additionally added field */
{ $project: { convertedId: 0 } }
])
Test : mongoplayground
Upvotes: 4