polar
polar

Reputation: 522

Meteor collection find and update value within object in subarray

I'm having some trouble determining how to find a document within a collection, and a value within an object in a subarray of that document — and then update a value within an object in that array.

I need to do the following:

For example, the documents in my collection are set up like below.

{
    "_id" : "mz32AcxhgBLoviRWs",
    "ratings" : [
        {
            "user" : "mz32AcxhgBLoviRWs",
            "post" : "SMbR6s6SaSfsFn5Bv",
            "postTitle" : "fdsfasdf",
            "date" : "2017-09-27",
            "rating" : "4",
            "review" : "sdfa",
            "report" : "a report"
        },
        {
            "user" : "mz32AcxhgBLoviRWs",
            "post" : "iZbjMCFR3cDNMo57W",
            "postTitle" : "today",
            "date" : "2017-09-27",
            "rating" : "4",
            "review" : "sdfa",
            "report" : "some report"
        }
    ]
}

Upvotes: 0

Views: 78

Answers (1)

Styx
Styx

Reputation: 10076

It seems that you want just one update, not three separated queries.

Collection.update({
  _id: <id>,
  ratings: {
    $elemMatch: {
      user: <user>,
      post: <post>
    }
  }
}, {
  $set: {
    'ratings.$.report': <report>
  }
});

Documentation: $elemMatch, <array>.$.

Upvotes: 3

Related Questions