【问题标题】:How to delete a specific sub-document from an array field in MongoDB?如何从 MongoDB 的数组字段中删除特定的子文档?
【发布时间】:2020-04-05 15:17:53
【问题描述】:

我一直在做一个项目,我想删除 mongodb 数组中的一个项目。 这是我的代码

    return new Promise(async(resolve, reject) => {
    await categoryCollection.findOne({_id : ObjectID(this.category_id)}, async (err, cat) => {
        let x = this.cat_slug
        if(!err) {
            cat.sub_categories.forEach(function(s_cat) {
                if (s_cat.slug == x) {
                    // here i need to delete the array
                }
            })
        } else {
            reject(err)
        }
    })
})

}

以我的 mongodb 集合为例

{
"_id" : ObjectId("5e89db06a4c8d06b8b8784ae"),
"author" : ObjectId("5e89db06a4c8d06b8b8784ad"),
"name" : "Design",
"slug" : "design",
"sub_categories" : [ 
    {
        "author" : ObjectId("5e89e3914ebca9658b4bdae4"),
        "name" : "Games",
        "slug" : "games",
        "created_at" : "2020-4-5-6:55:38",
        "updated_at" : "2020-4-5-6:55:38"
    }, 
    {
        "author" : ObjectId("5e89e39c4ebca9658b4bdae5"),
        "name" : "Photoshop",
        "slug" : "photoshop",
        "created_at" : "2020-4-5-6:55:38",
        "updated_at" : "2020-4-5-6:55:38"
    }
],
"created_at" : "2020-4-5-5:56:55",
"updated_at" : "2020-4-5-5:56:55"

}

我想删除 sub_categories 数组中的一个项目,当我单击删除按钮时,该项目将从我的模板引擎(按钮)中选择它我应该删除一个特定项目,如 sub_categories[0] 项目 i想删除它。

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    这可以帮助你。

    categoryCollection.update(
      { _id : ObjectID(this.category_id) },
      { $pull: 
        { 'sub_categories': 
          { "author": ObjectId("5e89e3914ebca9658b4bdae4") }
        }
      } 
    )
    

    仅当“作者”是唯一的时才有效。 如果不。为每个“sub_categories”添加唯一的 id。

    【讨论】:

    猜你喜欢
    • 2013-08-26
    • 2013-07-23
    • 2017-04-18
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2011-10-14
    相关资源
    最近更新 更多