3

I am attempting to push data into a nested array inside of a Mongo collection. I've followed along the Mongo documentation here, http://docs.mongodb.org/manual/reference/operator/update/positional/, but have not had any luck pushing into the array. No errors or exceptions are thrown and the syntax looks right...

In this example, I'm attempting to update the buyer.boards titled 'Board One' by pushing a new string into it's idArr array. Is there something wrong with my query?

Mongo Collection

// User Document from Meteor.users Collection:
{
    _id: 'userIdqwerty',
    buyer: {
        boards: [
            {
                title: 'Board One',
                idArr: ['id123', 'id456', 'id678']
            },
            {
                title: 'Board Two',
                idArr: ['idABC']
            },
            {
                title: 'Board Three',
                idArr: ['id12345678', 'idqwertyuu']
            },
        ]
    };
}

Javascript

var options = {
    boardTitle: 'Board One',
    newId: 'idZjodFsp',
    userId: 'userIdqwerty'
};

Meteor.users.update(
    { 
        _id:options.userId, 
        'buyer.boards.$.title':options.boardTitle 
    },
    { $push: { 
        'buyer.boards.$.idArr':options.newId }
    }
);

1 Answer 1

3

Remove the positional operator($) from the query parameter of the update function.

Meteor.users.update(
    { 
        _id:options.userId, 
        'buyer.boards.title':options.boardTitle 
    },
    { $push: { 
        'buyer.boards.$.idArr':options.newId }
    }
);

From the docs:

db.collection.update(
   { <array>: value ... },
   { <update operator>: { "<array>.$" : value } }
)

The positional operator should be used in the update parameter and not in the query parameter. This updates only the first boards object that has the matching title.

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.