![](/img/trans.png)
[英]Trouble with a PUT request not updating the entry using MongoDB, Node and Express
[英]Node rest API: put request is not updating the request data
嘗試使用 PUT 請求更新數據。 但是,數據不會更新並返回 postman 中的先前數據。
Postman 提出要求:
http://localhost:3000/api/actors/5daa8f1c5845ad0b5826b8d9?name=Tom
Postman 響應:
{
"createdAt": "2019-10-19T04:16:13.317Z",
"updatedAt": "2019-10-19T04:16:13.317Z",
"_id": "5daa8f1c5845ad0b5826b8d9",
"name": "scarlett johansson",
"birthday": "1980-10-14T00:00:00.000Z",
"country": "usa",
"__v": 0
}
我也嘗試過使用 findByIdAndUpdate。 沒有得到結果。 任何幫助,將不勝感激。
Controller:
exports.updateActor = async(req, res, next) => {
try {
const actorId = req.params.actorId;
const data = req.body;
const updateActor = await Actor.findById(actorId);
updateActor.set(data);
const actor = await updateActor.save();
// res.status(200).json({ message: "Data has Updated Successfully!" });
res.send(actor);
} catch (err) {
res.status(500).json({ message: err.message });
}
};
路由器:
router.put('/actors/:actorId', Actor.updateActor);
您的 postman 請求是http://localhost:3000/api/actors/5daa8f1c5845ad0b5826b8d9?name=Tom
所以看起來要更新的數據將在req.query
而不是req.body
中。
注意:您應該將要更新的數據放在正文中,而不是像您正在做的那樣查詢。
更多信息在這里。
Please use following code for getting update data
Actor.findOneAndUpdate({"_id":ObjectId(actorId)},data,
{ new: true}).then((updatedData) => {
res.send(updatedData);
});
要解決 ObjectId 錯誤,請使用以下代碼。
var mongoose = require('mongoose');
const updateActor = await Actor.findOneAndUpdate({"_id":mongoose.Types.ObjectId(actorId)},data, { new: true });
res.send(updateActor);
exports.updateActor = async(req, res, next) => {
try {
const actorId = req.params.actorId;
const data = req.body;
const updateActor = await Actor.update({"_id":actorId},data);
// res.status(200).json({ message: "Data has Updated Successfully!" });
res.send(updateActor);
} catch (err) {
res.status(500).json({ message: err.message });
}
};
try thiss...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.