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

1

1 Answer 1

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.

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.