简体   繁体   中英

Get and modify array sub document inside an array sub document

I have the following schema, where there is an array sub document that has another array sub document inside of it. How do I go about accessing or updating the claimed property of a specific winner id of a specific reward?

const eventSchema = new Schema({
    ...
    rewards: [{
        name: { type: String }
        winners: [{ 
            id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
            claimed: { type: Bolean }
        }] 
    }]
   ...
});

For example, in the document below, how to access a single winner from the winners array in a single reward from the rewards array.

{
    _id: "5f61132da98bac2a98487d79",
    rewards: [{  
            _id: "5f611378a98bac2a98487d7a",
            name: "First Reward"
            winners: [{
                    id: "5f611378a98bac2a98487d77",
                    claimed: false
                }, {
                    id: "5f61132da98bac2a98487d44",
                    claimed: false
                }, {
                    ...
                }]
        }, {
            ....
    }]
}

Or to be specific, how to update claimed status to true for a winners element having id: 5f611378a98bac2a98487d77 in a reward element having _id: 5f611378a98bac2a98487d7a ?

You can use $[<identifier>] to do this. Something like:

Model.updateOne(
  { _id: eventId }, 
  { $set: { "rewards.$[reward].winners.$[winner].claimed": true } },
  { arrayFilters: [ { 'reward._id': rewardId }, { 'winner.id': winnerId } ]}
)

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