简体   繁体   中英

updating subdocument array in mongoose express

So I have a schema, which is like this:

const playerSchema = new Schema(
      {
        user: {
          type: Schema.Types.ObjectId,
          ref: 'user'
        },
        paid : {type: Boolean, default: false}
      }
    )
const tournamentSchema = new Schema(
  {
    name: {
      type: String,
      required: true
    },
    player:[ playerSchema])

so in the tournament model i get this as return:

{
 "_id": "5fbf3afe1ecd92296c746db6",
 "name": "1st Testing Tournament",
 "player": [
        {
            "paid": false,
            "_id": "5fbf3cfe6347784028da8181",
            "user": "5fbf3b4c1ecd92296c746dcd"
        }
    ]}

in the API I will have only the user ID and the tournament ID. I want to update paid in players array from false to true. Here is what I tried:

exports.put_confirmPayment= async(req, res)=>{
    const uid = req.params.user_id
    const tid = req.params.tid
    const findData= {"_id": tid, "player.user": uid  }
    const changeData = {"player.$.paid": "true"}
    try {
        await Tournament.findOneAndUpdate( findData, {$set: {changeData}} )
        const tDB = await Tournament.findById(tid)
        res.status(200).json(tDB)
    } catch (error) {
        console.log(error)
        res.status(500).json(error.message)
    }
}

Where I am going wrong? and what should my approach be?

  • convert string id from string to object type using mongoose.Types.ObjectId
  • change "true" string to boolean true
  • return updated result using returnOriginal: false , or new: true both will return new updated result
  • have removed extra constant variables, don't create too much variables
exports.put_confirmPayment = async(req, res) => {

    try {
        const tDB = await Tournament.findOneAndUpdate(
          { 
            _id: mongoose.Types.ObjectId(req.params.tid), 
            "player.user": mongoose.Types.ObjectId(req.params.user_id) 
          }, 
          { $set: { "player.$.paid": true } },
          { returnOriginal: false }
        );
        res.status(200).json(tDB);
    } catch (error) {
        console.log(error);
        res.status(500).json(error.message);
    }

}

Playground

For more information refer mongoose findoneandupdate documentation.

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