Express 使用$pull删除子文档项
我试图使用ExpressJS和Mongoose从子文档中删除项,但它只是删除了第一个项,而不是子项 所以我想删除messages数组中的“subitem 2” 结构如下:Express 使用$pull删除子文档项,express,mongoose,pull,Express,Mongoose,Pull,我试图使用ExpressJS和Mongoose从子文档中删除项,但它只是删除了第一个项,而不是子项 所以我想删除messages数组中的“subitem 2” 结构如下: { "_id" : ObjectId("5c4ee94b30ebd71cbed89a35"), "title" : "Test", "subitem" : [ { "_id" : ObjectId("5c4ee95630ebd71cbed89a36"),
{
"_id" : ObjectId("5c4ee94b30ebd71cbed89a35"),
"title" : "Test",
"subitem" : [
{
"_id" : ObjectId("5c4ee95630ebd71cbed89a36"),
"title" : "Item 1",
"messages" : [
{
"_id" : ObjectId("5c4ee95f30ebd71cbed89a37"),
"type" : "single_article",
"date" : "Jan 28, 2019",
"title" : "subitem 1",
"text" : ""
}
]
},
{
"_id" : ObjectId("5c4ee96830ebd71cbed89a38"),
"title" : "item 2",
"messages" : [
{
"_id" : ObjectId("5c4ee96e30ebd71cbed89a39"),
"type" : "single_article",
"date" : "Jan 28, 2019",
"title" : "subitem 2",
"text" : ""
}
]
}
],
"__v" : 0
}
这是$pull方法:
getController.deleteRec = function(req,res,collection){
var id = req.params.id;
console.log(id);
collection.updateOne({'subitem.messages._id': id}, {$pull: {'subitem.0.messages': {"_id": id}}}).
then(function(result){
console.log(result);
});
};
现在我知道为什么它只删除第一项,因为我有“subitem.0.messages”。我如何循环这个,以便它可以删除所有项目?您可以使用
$
作为通配符索引,删除数组中与查询匹配的所有元素,如下所示:
{$pull: {'subitem.$.messages': {"_id": id}}}
如果要删除多个文档,请执行以下操作:
{$pull: {'subitem.$.messages': {"_id": {$in : [id, id2, id3...]}}}}