简体   繁体   English

更新 mongoose express 中的子文档数组

[英]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:所以在比赛 model 我得到这个作为回报:

{
 "_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.在 API 中,我将只有用户 ID 和锦标赛 ID。 I want to update paid in players array from false to true.我想将paid players数组从假更新为真。 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使用mongoose.Types.ObjectId将字符串 id 从字符串转换为 object 类型
  • change "true" string to boolean true将“true”字符串更改为 boolean true
  • return updated result using returnOriginal: false , or new: true both will return new updated result使用returnOriginal: falsenew: true返回更新的结果两者都将返回新的更新结果
  • 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.有关详细信息,请参阅mongoose 查找和更新文档。

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

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