black_sheep07
black_sheep07

Reputation: 2368

Mongoose $pull is deleting nested entire array instead of a single value in the array

I have a mongo schema that looks like this:

{
"_id" : ObjectId("58e4222497b2735ba3cd9ec4"),
"place" : "",
"plant" : "Test1",
"eventDate" : ISODate("2017-04-05T00:00:00Z"),
"event" : "Test123",
"toBeTested" : [
    {
        "_id" : ObjectId("58e453a07c9f94702ebac93d"),
        "thingsTested" : [
            "A1",
            "A2",
            "A3"
        ]
    }
]}

I'm using mongoose to remove a single element of thingsTested. My code in mongoose is:

Layout
    .update(
        {_id: req.params.parentid}, 
        {$pull: {toBeTested: {thingsTested: 'A3'}}},
        function (err, docs){
        if (err) {
            res.send(err);
        }
            res.json(docs);    
        }
    );

As you can see, I've hardcoded that I want to remove A3 from the thingsTested set. However, the exhibited behavior is that all of thingsTested is being deleted.

As a followup question, how can I make sure that the mongoose command only removes A3 in thingsTested with the _id of 58e453a07c9f94702ebac93d (the child ID)?

Thanks!

Upvotes: 2

Views: 624

Answers (1)

suddjian
suddjian

Reputation: 2406

You are going to have to select an outer array element in your query, and then the matched element can be referenced with a $, like so:

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

Upvotes: 1

Related Questions