Mongoose: Cast to ObjectId failed for value Mongoose: Cast to ObjectId failed for value mongoose mongoose

Mongoose: Cast to ObjectId failed for value


The example from the mongoose docs you referenced uses Number for the personSchema._id field, and ObjectId for the others.

I presume they do this in the example only to demonstrate that it's possible to use either. If you do not specify _id in the schema, ObjectId will be the default.

Here, all your records have an _id field which is an ObjectId, yet you're treating them like numbers. Furthermore, fields like personID and taskID do not exist, unless you've left out the part where you define them.

If you did want to use numbers for all your _id fields, you'd have to define that in the schemas.

var newsSchema = new Schema({  _id: Number,  _creator: {type: ObjectId, ref: "Person"},  // ...})var personSchema = new Schema({  _id: Number,  // ...})

Then to create a news item with a particular ID, and assign it to a creator:

var tony = new Person({_id: 0});var newsItem = new NewsItem({_id: 0, creator: tony.id});

However the thing to note here is that when you use something other than ObjectId as the _id field, you're taking on the responsibility of managing these values yourself. ObjectIds are autogenerated and require no extra management.

Edit: I also noticed that you're storing refs on both sides of your associations. This is totally valid and you may want to do it sometimes, but note that you'd have to take care of storing the references yourself in the pre hook.


I was receiving this error after creating a schema:CastError: Cast to ObjectId failed for value “[object Object]” at path “_id” Then modifying it and couldn't track it down. I deleted all the documents in the collection and I could add 1 object but not a second. I ended up deleting the collection in Mongo and that worked as Mongoose recreated the collection.


You have voters defined as an ObjectId ref, but you're trying to store an actual User representation inside it.

Assuming I understand your links correctly, you'll want to lookup the _id of the User by req.body.email, then make your update { $push: { voters: userId } } (where userId is the id of the User you found).