Home:ALL Converter>How to pull an element from an array of arrays in Mongo

How to pull an element from an array of arrays in Mongo

Ask Time:2020-04-08T17:59:11         Author:DanJHill

Json Formatter

I am struggling to find the format for a query to remove an element (with an _id) from an array of arrays in Mongo via Mongoose. I have read the Mongo documentation on pull and searched around, but cannot get the query format correct.

I know: the _id of the document in MySchema, the _id of the array element in outerArray, and the _id of the the array element in innerArray.

Could someone please point out what I am doing wrong? Thank you!

Mongo Schema:

MySchema {
    outerArray: [ {

        field1 : String,

        innerArray [ {

            field2: String

        } ]
    } ]
}

Mongoose Query - This does not work:

MySchema.findByIdAndUpdate( 
        mongoose.Types.ObjectId(docId),
        { 
            $pull: {
                'outerArray': {
                    $elemMatch: {
                        '_id': mongoose.Types.ObjectId(outerArrayDocId),
                        'innerArray': {
                            '_id': mongoose.Types.ObjectId(innerArrayDocId)
                        }
                    }
                }
            }
        },
        (err : mongoose.Error, updated : any) => {
});

Author:DanJHill,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/61098003/how-to-pull-an-element-from-an-array-of-arrays-in-mongo
yy