![](/img/trans.png)
[英]Mongodb checking exist field in an sub-document of an array using mongoose
[英]How to delete a specific sub-document from an array field in MongoDB?
好吧,我一直在做一個項目,我想刪除 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
數組中的一個項目,並且該項目將從我的模板引擎(按鈕)轉到 select 當我單擊刪除按鈕時,我應該刪除一個特定的項目,例如我想刪除的 sub_categories[0] 項目。
這可以幫助你。
categoryCollection.update(
{ _id : ObjectID(this.category_id) },
{ $pull:
{ 'sub_categories':
{ "author": ObjectId("5e89e3914ebca9658b4bdae4") }
}
}
)
只有當“作者”是唯一的時它才會起作用。 如果不。 為每個“子類別”添加唯一 ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.