Skip to content Skip to sidebar Skip to footer

Mongoose: Cast To Objectid Failed For Value

I'm trying to specify the schema of my db in mongoose. At the moment I do this: var Schema = mongoose.Schema; var today = new Date(2011, 11, 12, 0, 0, 0, 0); var personSchema =

Solution 1:

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 = newSchema({
  _id: Number,
  _creator: {type: ObjectId, ref: "Person"},
  // ...
})

var personSchema = newSchema({
  _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.

Solution 2:

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.

Post a Comment for "Mongoose: Cast To Objectid Failed For Value"