2

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

0

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.