簡體   English   中英

更新 mongoose express 中的子文檔數組

[英]updating subdocument array in mongoose express

所以我有一個模式,就像這樣:

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])

所以在比賽 model 我得到這個作為回報:

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

在 API 中,我將只有用戶 ID 和錦標賽 ID。 我想將paid players數組從假更新為真。 這是我嘗試過的:

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)
    }
}

我哪里錯了? 我的方法應該是什么?

  • 使用mongoose.Types.ObjectId將字符串 id 從字符串轉換為 object 類型
  • 將“true”字符串更改為 boolean true
  • 使用returnOriginal: falsenew: true返回更新的結果兩者都將返回新的更新結果
  • 移除了額外的常量變量,不要創建太多變量
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);
    }

}

操場

有關詳細信息,請參閱mongoose 查找和更新文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM