Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating array of objects in MERN stack

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

});

>Solution :

You are not awaiting the findOneAndUpdate:

const payprovision = await records.findOneAndUpdate( ... );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading