0

I'm trying to delete a subdocuments in array with Mongoose.

My datas :

{
    "_id": {
        "$oid": "5d88dfe45feb4c06a5cfb762"
    },
    "spaces": [{
        "_id": {
            "$oid": "5d88dfe45feb4c06a5cfb76f"
        },
        "name": "Building 2",
        "subSpace": [{
            "_id": {
                "$oid": "5d88dfe45feb4c06a5cfb771"
            },
            "name": "Basement"
        }, {
            "_id": {
                "$oid": "5d88dfe45feb4c06a5cfb770"
            },
            "name": "Floors"
        }]
    }, {
        "_id": {
            "$oid": "5d88dfe45feb4c06a5cfb76c"
        },
        "name": "Building 4",
        "subSpace": [{
            "_id": {
                "$oid": "5d88dfe45feb4c06a5cfb76e"
            },
            "name": "Basement"
        }, {
            "_id": {
                "$oid": "5d88dfe45feb4c06a5cfb76d"
            },
            "name": "Floors"
        }]
    }]
}

For this example, we want to delete the subSpace Floors in Building 2 with this _id : 5d88dfe45feb4c06a5cfb771

My code (in the model) :

exports.removeSubSpaceById = (subSpaceId) => {
    Residence.findOneAndUpdate( { "spaces.subSpace._id": '5d88dfe45feb4c06a5cfb771' },
        { $pull: 
        { spaces: 
        { subSpace: 
        { _id: '5d88dfe45feb4c06a5cfb771' }}}}, function(err, result) {
            console.log(result);
    })
};

Output : console.log : my entire document But the subSpace/Basement (5d88dfe45feb4c06a5cfb771) is still in my document.

Thanks for your help.

1 Answer 1

1

Use positional operator for nested array operations. MongoDb Docs

exports.removeSubSpaceById = (subSpaceId) => {
Residence.findOneAndUpdate({ "spaces._id": '5d88dfe45feb4c06a5cfb76f' },
    {
        $pull:
        {
            "spaces.$.subSpace": { _id: "5d88dfe45feb4c06a5cfb771" }
        }
    }, function (err, result) {
        console.log(result);
    })

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.