Dinesh
Dinesh

Reputation: 33

how to set mongo objectId field to null or empty or even delete the field?

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:

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

Answers (3)

Rajnish
Rajnish

Reputation: 177

Use Below line document.category = new MongoDB\BSON\ObjectID('');

Upvotes: 0

Sravan
Sravan

Reputation: 18647

Try unsetting the document

document.update({_id: "5dsfkjh2r74dsjdhf3r4f"}, {$unset: {category: 1 }});

or

document.update({_id: ObjectId("5dsfkjh2r74dsjdhf3r4f")}, {$unset: {category: 1 }});

Upvotes: 5

Anurag Awasthi
Anurag Awasthi

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

Related Questions