0

I am trying to teach myself Meteor and Mongo. I have a particular insertion inside my Meteor method that is driving me nuts.

My document object looks like this:

{
    _id
    name: "name",
    stuff: {},
    array: [
        {
            id: 0,
            target:[
                {
                    id: 0,
                    name: "1"
                },{
                    id: 1,
                    name: "2"
                }
            ]
        },{
            id: 1,
            target:[
                {
                    id: 0,
                    name: "A"
                },{
                    id: 1,
                    name: "B"
                }
            ]
        }
    ],
}

I am trying to add objects into the target array, which is inside an object inside the array-array.

I have tried a number of different approaches over a few days based on some things I have seen here on stack overflow. The most recent attempt is:

Documents.update({_id: id, 'array.id': arrayId}, {$addToSet:{'array.$.target': objectToInsert}},{upsert: false, multi: false})

If anyone could point me in the right direction I would appreciate it.

Norl
  • 11
  • 2

2 Answers2

0

Seems this could be an issue with where you are doing the update. If this is on the client, then see here:

Update an subdocument contained in an array contained in a MongoDB document

Solution is to move this to the server.

Also, you may want to look at the difference between $addToSet and $push here MongoDb: Difference between $push/$addtoset

If this is not on the client side and changing to push does not fix your issue, can you add to your question what the error is.

Community
  • 1
  • 1
Shaun Stoltz
  • 166
  • 1
  • 2
0

I donot know the mongo query to do something like this but it can be done as below

let theArray=Document.findOne({_id:id}).array,
arrayOfIds=_.pluck(theArray,"id"),
index=_.indexOf(arrayOfIds,arrayId),
theArray[index].target.push(objectTobeInserted)

Now update the document with the modified array

Document.update({_id:id},{$set:{array:theArray})

If you donot understand _.pluck and _.indexOf, you can refer to underscorejs

khem poudel
  • 587
  • 7
  • 13