Home > Blockchain >  Return invalid data in response in Node Js API
Return invalid data in response in Node Js API

Time:05-10

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

{
    "_id": "627985c905dcb255365a2c0e",
    "fullName": "Thambili Kankanamlage Ruwan Rohitha",
    "nic": "2021345475655",
    "address": "Old air port road, Nagoda, Kalutara",
    "telephone": "0761234567",
    "email": "[email protected]",
    "__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"

CodePudding user response:

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

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

  • Related