1

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?

1 Answer 1

3
  • 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.