Mongoose $ pull是删除嵌套的整个数组,而不是数组中的单个值
我有一个如下所示的mongo模式:
{ "_id" : ObjectId("58e4222497b2735ba3cd9ec4"), "place" : "", "plant" : "Test1", "eventDate" : ISODate("2017-04-05T00:00:00Z"), "event" : "Test123", "toBeTested" : [ { "_id" : ObjectId("58e453a07c9f94702ebac93d"), "thingsTested" : [ "A1", "A2", "A3" ] } ]}
我正在使用mongoose删除thingsTested
单个元素。 我在mongoose的代码是:
Layout .update( {_id: req.params.parentid}, {$pull: {toBeTested: {thingsTested: 'A3'}}}, function (err, docs){ if (err) { res.send(err); } res.json(docs); } );
正如你所看到的,我已经硬编码了,我想从thingsTested
集中删除A3
。 然而,展出的行为是所有thingsTested
被testing被删除。
作为一个后续问题,我怎样才能确保thingsTested
命令只删除A3
的thingsTested
与_id
58e453a07c9f94702ebac93d
(儿童ID)?
谢谢!
你将不得不在你的查询中select一个外部数组元素,然后匹配的元素可以用$
来引用,如下所示:
// ▼ selecting the toBeTested element update({_id: req.params.parentid, 'toBeTested.thingsTested': 'A3'}, // ▼ referencing the selected element {$pull: {'toBeTested.$.thingsTested': 'A3'}}});