Reputation: 33
My Modal :
{
"name":{type:String,required:true},
"category":{type:mongoose.Schema.Types.ObjectId,ref:"Category"}
}
I have a document created using this modal and the document looks like:
{
"_id":ObjectId("5dsfkjh2r74dsjdhf3r4f"),
"name":"demo 1",
"category":ObjectId("5ae9dlkj32nds6n37cj23")
}
If I try to change the category field, for eg:
document.category = ''
document.category = null
document.category = undefined
I'm getting the following error:
Cast toObjectId failed ...
I need to unset the "category"
field to null
or empty
or even delete it. How to do that?
Upvotes: 3
Views: 14144
Reputation: 18647
Try unsetting
the document
document.update({_id: "5dsfkjh2r74dsjdhf3r4f"}, {$unset: {category: 1 }});
or
document.update({_id: ObjectId("5dsfkjh2r74dsjdhf3r4f")}, {$unset: {category: 1 }});
Upvotes: 5
Reputation: 6233
ObjectId
should be a 24 length string which I guess your id
is not. That's why mongo cannot convert it into valid ObjectId
.
One solution would be to generate 24 character valid ObjectId
for category field.
Other would be to set category
as a simple String
instead of ObjectId
Upvotes: 0