0

I have a schema in Mongoose:

const member = new Schema({
  _id: { type: String, required: true },
  ...
});

but when I use await MemberModel.findOne({ _id: req.params.userID }); in an express request handler, I get a CastError: Cast to ObjectId failed for value "MY_SECRET_VALUE" at path "_id" for model "Member".

As you can see, I have set _id's type to String in the Schema - why is it not allowing me to search for the _id by a String value?

Jacques Amsel
  • 1,061
  • 2
  • 14
  • 30
  • 1
    You need `{ _id: false }` in the "schema options" ( the second argument to the `Schema` function ). Without it, mongoose will still attempt to use it's "built in" methods for validating input for `_id`, which of course it expects to an `ObjectId` by default. – Neil Lunn Oct 27 '19 at 10:58
  • Thank you - the first answer on the duplicate doesn't say that this is necessary as far as I understand. – Jacques Amsel Oct 27 '19 at 11:01
  • 1
    Well the "first" or even accepted one is not necessarily the correct one ( and in due fairness, the API has changed a bit since the "first" answer was written ). Other answers there do say this is necessary, but *may not* embellish as to why. Hence the comment from myself to clarify. – Neil Lunn Oct 27 '19 at 11:06

1 Answers1

0

I am not an expert but to get the id in mongoose

you have to make the type equal to mongoose.Schema.Types.ObjectId

type : mongoose.Schema.Types.ObjectId 
  • This is not an answer to the question that was asked. A non-ObjectId value needs to be stored in _id, therefore `type` is a `String` – Jacques Amsel Oct 27 '19 at 10:36