Return Node Js 中的响应数据无效 API
Return invalid data in response in Node Js API
我正在尝试更新用户并使用节点 js 在 mongo Db 中获取更新的数据。数据库数据正在更新,但我得到的响应是过时的数据。
这是我的更新函数
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" })
})
}
这是数据库用户数据
{
"_id": "627985c905dcb255365a2c0e",
"fullName": "Thambili Kankanamlage Ruwan Rohitha",
"nic": "2021345475655",
"address": "Old air port road, Nagoda, Kalutara",
"telephone": "0761234567",
"email": "ruwan@gmail.com",
"__v": 0
}
当我更新任何字段(例如 'nic' 为“5433243532324”)时,尽管数据库已更新,但我得到以前的数据作为响应
像这样 "nic": "2021345475655"
但我想要这样 "nic": "5433243532324"
您必须使用新的 属性 传递选项对象才能获取更新的数据
studentDB.findByIdAndUpdate(id, req.body,{new:true})
我正在尝试更新用户并使用节点 js 在 mongo Db 中获取更新的数据。数据库数据正在更新,但我得到的响应是过时的数据。
这是我的更新函数
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" })
})
}
这是数据库用户数据
{
"_id": "627985c905dcb255365a2c0e",
"fullName": "Thambili Kankanamlage Ruwan Rohitha",
"nic": "2021345475655",
"address": "Old air port road, Nagoda, Kalutara",
"telephone": "0761234567",
"email": "ruwan@gmail.com",
"__v": 0
}
当我更新任何字段(例如 'nic' 为“5433243532324”)时,尽管数据库已更新,但我得到以前的数据作为响应
像这样 "nic": "2021345475655"
但我想要这样 "nic": "5433243532324"
您必须使用新的 属性 传递选项对象才能获取更新的数据
studentDB.findByIdAndUpdate(id, req.body,{new:true})