Sasikanth
Sasikanth

Reputation: 3043

nested array inserting in mongodb?

I am using Meteor where I have a mongodb document where something inserted with the following code:

Poll_Coll.insert({question:quest,option1:[{pd:op1,ids:[]}],
        option2:[{pd:op2,ids:[]}],
        option3:[{pd:op3,ids:[]}],
        option4:[{pd:op4,ids:[]}]});

I want to update multiple ids in the option1.ids array, which I tried to do like this:

Polls_Coll.update({_id:"xxxx","option1.pd":"xxx"},{$push:{"option1.$.ids":6}});
Polls_Coll.update({_id:"xxxxx","option1.pd":"xxx"},{$push:{"option1.$.ids":{id:"ya"}}});

option1.pd is working perfectly. I tried both the above commands and am getting the error

Error: MinimongoError: can't append to array using string field name [$] [409]

How do I insert into that ids field?

Upvotes: 2

Views: 1944

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151072

The issue is with the minimongo implementation being used by meteor as it currently does not support the positional $ operator.

From the following data sample the operations are working in the mongo shell

{
    "_id" : ObjectId("52eb0a6542b2498fd49f4f28"),
    "question" : "quest",
    "option1" : [
            {
                    "pd" : "op1",
                    "ids" : [ ]
            },
            {
                    "pd" : "op7",
                    "ids" : [ ] 
            }
    ],
    "option2" : [
            {
                    "pd" : "op2",
                    "ids" : [ ]
            }
    ],
    "option3" : [
            {
                    "pd" : "op3",
                    "ids" : [ ]
            }
    ],
    "option4" : [
            {
                    "pd" : "op4",
                    "ids" : [ ]
            }
    ]
}

Applying the following statement will push values onto the matching element's 'ids' array.

db.poll.update({"option1.pd": "op1"},{$push: { "option1.$.ids": 6 }})

Basically the same code will work server side as well.

It would seem the solution would be to wrap this update in a function call that can be invoked from the client and execute the code on the server.

Here are some links confirming the issue:

https://github.com/meteor/meteor/issues/153

https://github.com/meteor/meteor/blob/master/packages/minimongo/NOTES

Upvotes: 3

Related Questions