简体   繁体   English

流星集合在子数组中的对象内查找和更新值

[英]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 通过_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. 似乎您只需要一个update ,而不是三个分开的查询。

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

Documentation: $elemMatch , <array>.$ . 文档: $elemMatch<array>.$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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