Mongodb upsert howto insert checkbox array


#1

Hi,

I have a friendlist with checkboxes, where you can check a checkbox if a person is invited to a event.

if I have checked to persons my console log give me : [ ‘FjoBeedAQvJYSxgAs’, ‘TTHyxmmpdqzpmGttc’ ]

my submit meteor call

submit () {
              console.log(this.thepeople);
               
              Meteor.call('addinvite',this.thepeople, function(error, response) {});
  

my method in main.js server

  addinvite: function(thepeople) {

      console.log(thepeople);
      let meteorUser = Meteor.userId();
      EventInvited.upsert(
        {userId: meteorUser},
        {$addToSet:{invitedId: thepeople } }
        );
  },

That will give me this wrong one

{
    "_id" : "7kP4oFngCZ8tQ9EED",
    "userId" : "v4b7cSa3uHqDk4Nm9",
    "invitedId" : [ 
        [ 
            "TTHyxmmpdqzpmGttc"
        ], 
        [ 
            "FjoBeedAQvJYSxgAs", 
            "TTHyxmmpdqzpmGttc"
        ]
    ]
}

The problem is that if I add new people it addeds it in [USERID], and not in one

How to make it like this:

{
    "_id" : "7kP4oFngCZ8tQ9EED",
    "userId" : "v4b7cSa3uHqDk4Nm9",
    "invitedId" :   [ 
            "FjoBeedAQvJYSxgAs", 
            "TTHyxmmpdqzpmGttc",
            "USERID",
    ]
}

OR better like this:

{
"_id" : "v4b7cSa3uHqDk4Nm9",
  "invitedId" : [ 
        {
            "userid" : "FjoBeedAQvJYSxgAs",
            "status" : 0
        }, 
        {
            "userid" : "TTHyxmmpdqzpmGttc",
            "status" : 0
        }, 
 ]

}

#2

Looks like it is inserting the array instead of the elements of the array.

Use $each to insert each element:

EventInvited.upsert(
    { userId: meteorUser },
    { $addToSet:{ invitedId: { $each: thepeople } } }
);

https://docs.mongodb.com/manual/reference/operator/update/each/


#3

Perfect thanks, have used each before but have just forgot that I had to use it