简体   繁体   中英

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:

  • find by _id

  • find object in ratings array that matches the user + post keys

  • update the report value within that object

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"
        }
    ]
}

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>.$ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM