Home > Blockchain >  Updating array of objects in MERN stack
Updating array of objects in MERN stack

Time:08-16

This is what an object in my "records" model looks like:

{
   "_id":"62f937aa0ed0f743593714b2",
   "amount":50000,
   "provisionMonths":[
      {
         "month":"October 2022",
         "status":-1,
         "monthlyAmount":10000,
         "_id":"62f937aa0ed0f743593714b3"
      },
      {
         "month":"November 2022",
         "status":-1,
         "monthlyAmount":10000,
         "_id":"62f937aa0ed0f743593714b4"
      },
      {
         "month":"December 2022",
         "status":-1,
         "monthlyAmount":10000,
         "_id":"62f937aa0ed0f743593714b5"
      }       
   ],
}

I'm trying to update the status field to 1 when the user clicks on the pay button. However the server returns status code 422.

Client side code:

 const payMonthlyProvision = async (ID, id) => {
    // e.preventDefault();

    const res3 = await fetch(`/payprovision/${ID}/${id}`, {
        method: "PATCH",
        headers: {
            "Content-Type": "application/json"
        }
 
    });

    const data2 = await res3.json();
    console.log(data2);
    console.log(ID, id)

    if (res3.status === 422) {
        console.log(res3);
    } else {
        alert('success')
    }
}

button: <button onClick={() => payMonthlyProvision(getRecordData._id, item._id)}>Pay</button>

router code:

router.patch("/payprovision/:ID/:id", async (req, res) => {
try {
    const { ID, id } = req.params;

    const payprovision = records.findOneAndUpdate(
        { _id: ID },
        { $set: { "provisionMonths.$[el].status": 1 } },
        {
            arrayFilters: [{ "el._id": id }],
            new: true
        }
    )

    console.log(payprovision);
    res.status(201).json(payprovision);
} catch (error) {
    res.status(422).json(error);
}

});

CodePudding user response:

You are not awaiting the findOneAndUpdate:

const payprovision = await records.findOneAndUpdate( ... );

Also, if you want to update the amount property try with:

const newAmount = 10;

const payprovision = await records.findOneAndUpdate(
  { _id: ID },
  {
    $set: { amount: newAmount, 'provisionMonths.$[el].status': 1 },
  },
  {
    arrayFilters: [{ 'el._id': id }],
    new: true,
  }
);
  • Related