mongoose update array or add to the array

后端 未结 2 1548
刺人心
刺人心 2021-01-27 09:28

I\'ve been trying to get this running for a while now but I can\'t figure out what I\'m doing wrong.

I have two schemas like this

const paymentSchema = n         


        
2条回答
  •  轮回少年
    2021-01-27 10:22

    Consider the two input documents. The first one will be inserted (the year_month: '2020_03' doesn't exist in the payments array). When the update is run with the second one it will update the statusof the existing sub-document in the array.

    The update operation is valid with the MongoDB version 4.2 or later only, as it uses a pipeline for the update.

    INPUT_DOC = { year_month: '2020_03', status: false }    // this will get inserted into the array
    INPUT_DOC = { year_month: '2020_02', status: true }     // updates the sub-document
    
    db.collection.findOneAndUpdate(
      { 
          _id: "5e90ae0e0ed9974174e92826" 
      },
      [ 
          { 
              $set: { 
                  payments: {
                      $reduce: {
                          input: "$payments", 
                          initialValue: { payments: [], update: false },
                          in: {
                              $cond: [ { $eq: [ "$$this.year_month", INPUT_DOC.year_month ] },
                                       { 
                                          payments: { 
                                              $concatArrays: [
                                                   [ { _id: "$$this._id", year_month: "$$this.year_month", status: INPUT_DOC.status } ],
                                                   "$$value.payments"
                                               ] 
                                          }, 
                                          update: true
                                       },
                                       { 
                                          payments: { 
                                              $concatArrays: [  [ "$$this" ], "$$value.payments" ] 
                                          }, 
                                          update: "$$value.update" 
                                       }
                              ]
                          }
                      }
                  }
              }
          },
          { 
              $set: { 
                  payments: { 
                      $cond: [ { $eq: [ "$payments.update", false ] },
                               { $concatArrays: [ [ INPUT_DOC ], "$payments.payments" ] },
                               { $concatArrays: [ [ ], "$payments.payments" ] }
                      ] 
                  }
              }
          }
      ],
      { 
          new: true, 
          upsert: true 
      }
    )
    

提交回复
热议问题