0

mongodb 3.0.7 mongoose 4.1.12

I want to push new element : "bbb" onto groups array which lives inside outer orgs array ...

original mongo data from this :

{
    orgs: [
        {
            org: {
                _bsontype: "ObjectID",
                id: "123456789012"
            },
            groups: [
                "aaa"
            ]
        }
    ],
    _id: {
        _bsontype: "ObjectID",
        id: "888888888888"
    }
}

to this :

{
    orgs: [
        {
            org: {
                _bsontype: "ObjectID",
                id: "123456789012"
            },
            groups: [
                "aaa",
                "bbb"
            ]
        }
    ],
    _id: {
        _bsontype: "ObjectID",
        id: "888888888888"
    }
}

Here is a hardcoded solution yet I do not want to hardcode array index (see the 0 in : 'orgs.0.groups' )

dbModel.findByIdAndUpdate(

    { _id: ObjectId("888888888888".toHex()), 'orgs.org' : ObjectId("123456789012".toHex()) },
    {   $push : { 'orgs.0.groups' : 'bbb'  
                }
    },
    {   safe: true, 
        upsert: false, 
        new : true
    }
)

... I was hoping a simple 'orgs.$.groups' would work, but no. Have also tried 'orgs.groups' , also no. Do I really need to first retrieve the orgs array, identify the index then perform some second operation to push onto proper orgs array element ?

PS - suggested duplicate answer does not address this question

Scott Stensland
  • 26,870
  • 12
  • 93
  • 104
  • Possible duplicate of [Update all elements in an array in mongodb](http://stackoverflow.com/questions/33186596/update-all-elements-in-an-array-in-mongodb) – styvane Oct 21 '15 at 15:22

1 Answers1

1

Found solution, had to use

dbModel.update 

not

dbModel.findOneAndUpdate nor dbModel.findByIdAndUpdate

when using '$' to indicate matched array index in multi-level documents

'orgs.$.groups'

this code works :

dbModel.update(

    { _id: ObjectId("888888888888".toHex()), 'orgs.org' : ObjectId("123456789012".toHex()) },
    {   $push : { 'orgs.$.groups' : 'bbb'  
                }
    },
    {   safe: true, 
        upsert: false, 
        new : true
    }
)

I wonder if this is a bug in mongoose ? Seems strange findOneAndUpdate fails to work.

Scott Stensland
  • 26,870
  • 12
  • 93
  • 104