Node.js Mongoose$pull正在删除嵌套的整个数组,而不是数组中的单个值

Node.js Mongoose$pull正在删除嵌套的整个数组,而不是数组中的单个值,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个mongo模式,如下所示: { "_id" : ObjectId("58e4222497b2735ba3cd9ec4"), "place" : "", "plant" : "Test1", "eventDate" : ISODate("2017-04-05T00:00:00Z"), "event" : "Test123", "toBeTested" : [ { "_id" : ObjectId("58e453a07c9f94702ebac93d"),

我有一个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删除
thingstestested
的单个元素。我在猫鼬中的代码是:

Layout
    .update(
        {_id: req.params.parentid}, 
        {$pull: {toBeTested: {thingsTested: 'A3'}}},
        function (err, docs){
        if (err) {
            res.send(err);
        }
            res.json(docs);    
        }
    );
正如您所看到的,我已经硬编码了,我想从
thingstestested
集中删除
A3
。然而,所展示的行为是所有的
thingstestested
都被删除

作为后续问题,我如何确保mongoose命令仅删除
thingstestested
中的
A3
,并使用
58e453a07c9f94702ebac93d
\u id
(子id)


谢谢

您必须在查询中选择一个外部数组元素,然后可以使用
$
引用匹配的元素,如下所示:

//                                 ▼ selecting the toBeTested element
update({_id: req.params.parentid, 'toBeTested.thingsTested': 'A3'}, 
//                          ▼ referencing the selected element
       {$pull: {'toBeTested.$.thingsTested': 'A3'}}});

可能重复nah,为此使用位置运算符将是不正确的。如何将引用添加到特定的
thingstestested
\u id
58e453a07c9f94702ebac93d
)?我不确定您的确切意思,因为示例数据中的
thingstestested
元素没有
\u id
,但我认为您只需要将其放在查询中的某个位置,以便只匹配具有该id的文档。可能类似:
{{u-id:req.params.parentid,'toBeTested.thingstestested':'A3','toBeTested.thingsTested.A3.\u-id':[id]}
。您可以向查询中添加任意数量的参数,它只会匹配匹配所有参数的文档。很抱歉,我实际上是说
toBeTested
有一个
\u id
。但是这很有帮助!谢谢!只是为了澄清一下。您在更新部分使用了
$
位置运算符。您必须使用
elemMatch
在多个字段上匹配,即
toBeTested
数组中的
\u id
thingstestested
布局。更新({'toBeTested':{'elemMatch':{'u id':ObjectId(“58e453a07c9f94702ebac93d”),“thingsTested”:“A3”},{$pull:{'toBeTested.$.thingstestested':“A3”}
。查询部分将把
$
解析为具有匹配元素的索引。在您的情况下,它将是0,update将使用此索引从数组中提取
A3