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

Return invalid data in response in Node Js API

I’m trying to update a user and get the updated data in mongo Db using node js. The database data is updating but I’m getting outdated data as the response.

This is my update function

exports.update = (req, res) => {
    if (!req.body) {
        res.status(400).send({ message: "Content cannot be empty" })
        return
    }

    const id = req.params.id

    studentDB.findByIdAndUpdate(id, req.body)
        .then(data => {
            if (!data) {
                res.status(404).send({ message: `Cannot update user with ${id}. Maybe user not found!` })
            } else {
                res.send(data)
            }
        })
        .catch(err => {
            res.status(500).send({ message: err.message || "Some error occured while creating a update method" })
        })
}

This is the database user data

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

{
    "_id": "627985c905dcb255365a2c0e",
    "fullName": "Thambili Kankanamlage Ruwan Rohitha",
    "nic": "2021345475655",
    "address": "Old air port road, Nagoda, Kalutara",
    "telephone": "0761234567",
    "email": "ruwan@gmail.com",
    "__v": 0
}

When I update any field (example ‘nic’ as ‘5433243532324’) I get the previous data as a response although the database is updated

Like this "nic": "2021345475655"

But I want it like this "nic": "5433243532324"

>Solution :

You have to pass options object with new property to get updated data

studentDB.findByIdAndUpdate(id, req.body,{new:true})

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