0

I am trying to update a collection based on multiple _id's.

I recieve the _id's in an array format via a Session.get() as below:

 var selectedID = Session.get('selectedItemIDSet');

 console.log("selectedID array contents are: "+selectedID); 

The code above ensures that the selectedID array exists and yields:

selectedID array contents are: LZJKA8S3wYNwHakzE,ikrbCDuttHrwkEcuv

The Query below:

buyList.find({_id:{ "$in": selectedID} }).fetch(); 

Successfully yeilds two Objects!

Now to area am having issues with, how to I update the collection with these two _id's

I have tried with the below code:

var PostedArray = [{PostedBy: Meteor.user()._id }];
buyList.update(_id: selectedID, {$set: {wishListArray: PostedArray} });

...but get error message: Uncaught Error: Mongo selector can't be an array.(…)

Any help would be appreciated.

SirBT
  • 1,580
  • 5
  • 22
  • 51

1 Answers1

2

Use the same selector in your update as you have done for your find + specify the multi: true option:

buyList.update({ // selector
  _id: {
    "$in": selectedID
  }
}, { // modifier
  $set: {
    wishListArray: PostedArray
  }
}, { // options
  multi: true
});

Note that your 2 documents will be updated with the same modifier.

ghybs
  • 47,565
  • 6
  • 74
  • 99
  • 1
    You'll also want to add ```{multi: true}``` to the end to make sure more than 1 document is updated. So the final code would be ```buyList.update({ _id: { "$in": selectedID }}, { $set: { wishListArray: PostedArray }}, { multi: true });``` – Sean Apr 14 '17 at 16:18
  • @ghybs Thanks guys. Following your advice, am getting this error message: Uncaught. errorClass {error: 403, reason: "Not permitted. Untrusted code may only update documents by ID." , details: undefined, message: "Not permitted. Untrusted code may only update documents by ID. [403]", errorType: "Meteor.Error"} – SirBT Apr 14 '17 at 19:53
  • @SirBT Where are you executing your code? Do you still have `insecure` package? – ghybs Apr 14 '17 at 19:57
  • @ghybs I am executing the code on the chrome browser console, which am assuming is equivalent to running it on the client side. No, I don't have insecure package. I removed that a while ago. – SirBT Apr 14 '17 at 21:25
  • See http://stackoverflow.com/questions/15464507/understanding-not-permitted-untrusted-code-may-only-update-documents-by-id-m – ghybs Apr 15 '17 at 03:30
  • @ghybs thanks! Once I moved it to the server side, it worked. Thanks a bunch! – SirBT Apr 15 '17 at 21:46