最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to set mongo objectId field to null or empty or even delete the field? - Stack Overflow

programmeradmin1浏览0评论

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('');

发布评论

评论列表(0)

  1. 暂无评论