0

我正在尝试更新数组内的子文档。

{
    "_id" : ObjectId("5a7a017e0aa5311d9c75c86b"),
    "campaignId" : "5a7a017e0aa5311d9c75c86b",
    "subCampaigns" : [ 
        {
            "_id" : ObjectId("5a7a0eee6849f507d0499a18"),
            "name" : "test5",
            "campaignId" : ObjectId("5a7a017e0aa5311d9c75c86b"),
            "subCampaignId" : "1aKysewspn6CqNGVkv6pyL"
        }
        {
            "name" : "test8",
            "amountRaised" : 20.0,
            "campaignId" : ObjectId("5a7a017e0aa5311d9c75c86b"),
            "subCampaignId" : "5a7a153fe035de396c6f5b3c",
            "_id" : ObjectId("5a7a153fe035de396c6f5b3c")
        }
    ],
    "name" : "test8",
    "__v" : 12,
    "totalDonated" : 110.0
}

当我运行时:

db.getCollection('campaigns').update({"_id": ObjectId("5a7a017e0aa5311d9c75c86b"), "subCampaigns.subCampaignId":"5a7a153fe035de396c6f5b3c"}, {$inc: {"subCampaigns.$.amountRaised": 10}})

在 mongo 控制台中,它可以很好地更新子文档。但是当我在我的 Mongoose 代码中运行它时:

this.campaignModel.update(
          { campaignId: '5a7a017e0aa5311d9c75c86b', 'subCampaigns.subCampaignId': '5a7a153fe035de396c6f5b3c' },
          { $inc: { 'subCampaigns.$.amountRaised': 10}},
          (err: any, subResult: any) => {...

子文档的 amountRaised 字段没有增加。据我所知,他们应该是相同的电话?

如果我在更高级别经营一家公司:

this.campaignModel.findOneAndUpdate(
                {campaignId: object.campaignId},
                {$inc: {totalDonated: donationAmount}},
                () => {...

它工作正常,所以这一定与子文档有关?在一天的大部分时间里,我一直在玩多个猫鼬电话,但似乎无法让它正确更新。

4

0 回答 0