Home > front end >  Update document inside array of objects in mongoose
Update document inside array of objects in mongoose

Time:08-15

I need to update objects inside an array so I'm trying but I get the following error:

error Plan executor error during findAndModify :: caused by :: The positional operator did not find the match needed from the query.

This is my code:

        const payment = await Purchase.findByIdAndUpdate( 
        { '_id': req.body.id, 'payments._id': req.body.paymentId },
        {
          $set: {
            'payments.$.status': false
          }
        }
        ,{ new: true });

payments object on Model:

 payments: [
    {
      createdBy: [Object],
      createdAt: '08/13/22',
      paymentNumber: 0,
      previousBalance: 3747.68,
      paymentAmount: 3747.68,
      outstandingBalance: 0,
      status: true,
      _id: new ObjectId("62f83f3c22e4f67dde8cb85a"),
      lastModificationBy: [],
      disabledBy: []
    }
  ]

CodePudding user response:

while using fineByIdAndUpdate you only need to pass id of document to be updated.

const payment = await Purchase.findByIdAndUpdate(req.body.paymentId,{status:false},{new:true} )

CodePudding user response:

for using fineByIdAndUpdate, you need to add this runValidators

const payment = await Purchase.findByIdAndUpdate(req.params.id, 
            'payments.$.status': false
          }, {runValidators: true}

while same update can be done by this as well

const payment = await Purchase.findByIdAndUpdate(req.body.paymentId,{status:false},{new:true} )```
  • Related