Avi A
Avi A

Reputation: 323

Updating object inside an array of objects

I have an object with an array of objects like that:

//restMenuType({_id: 'abcde', hasItems: [{itemId: 'a', sortId: 1}, {itemId: 'b', sortId: 2}]})

I am trying to replace the sortId key on both objects:

'replaceItemsPositionUp': function(typeId, prevId, curId, prevSortId, curSortId){
        RestMenuTypes.update({
            _id: typeId,
            hasItems: {$elemMatch: {itemId: curId}}},
            {$set: {'hasItems.sortId': prevSortId}}
        );
        RestMenuTypes.update({
                _id: typeId,
                hasItems: {$elemMatch: {itemId: prevId}}},
            {$set: {'hasItems.sortId': curSortId}}
        );

    }

What is thee right way to do it? Thanks.

Upvotes: 0

Views: 2715

Answers (1)

Avi A
Avi A

Reputation: 323

That's the way to do it: Found it here: Update field in exact element array in MongoDB

RestMenuTypes.update({
            _id: typeId,
            'hasItems.itemId': curId},
            {$set: { "hasItems.$.sortId": prevSortId}}
        );
        return RestMenuTypes.update({
                _id: typeId,
                'hasItems.itemId': prevId},
            {$set: {'hasItems.$.sortId': curSortId}}
        );

Upvotes: 2

Related Questions