admin管理员组

文章数量:1302929

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?

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?

Share Improve this question edited Mar 16, 2018 at 10:21 Philipp Maurer 2,5056 gold badges20 silver badges26 bronze badges asked Mar 16, 2018 at 9:59 DineshDinesh 331 gold badge1 silver badge5 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Try unsetting the document

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

or

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

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

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

本文标签: javascripthow to set mongo objectId field to null or empty or even delete the fieldStack Overflow