为了账号安全,请及时绑定邮箱和手机立即绑定

节点休息 API:放置请求未更新请求数据

节点休息 API:放置请求未更新请求数据

森林海 2021-11-25 19:48:05
尝试使用 PUT 请求更新数据。但是,数据不会更新并返回邮递员中的先前数据。邮递员提出请求:http://localhost:3000/api/actors/5daa8f1c5845ad0b5826b8d9?name=Tom邮递员回复:{    "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。没有得到结果。任何帮助,将不胜感激。控制器: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);
查看完整描述

3 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

要解决 ObjectId 错误,请使用以下代码。


var mongoose = require('mongoose');

const updateActor = await Actor.findOneAndUpdate({"_id":mongoose.Types.ObjectId(actorId)},data, { new: true });

res.send(updateActor);


查看完整回答
反对 回复 2021-11-25
?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

您的邮递员请求http://localhost:3000/api/actors/5daa8f1c5845ad0b5826b8d9?name=Tom看起来像是要更新的数据req.query而不是req.body.

注意:您应该将要更新的数据放在正文中,而不是像您现在所做的那样进行查询。

更多信息在这里


查看完整回答
反对 回复 2021-11-25
?
白衣非少年

TA贡献1155条经验 获得超0个赞

Please use following code for getting update data 


 Actor.findOneAndUpdate({"_id":ObjectId(actorId)},data, 

 { new: true}).then((updatedData) => {

 res.send(updatedData);

 });


查看完整回答
反对 回复 2021-11-25
  • 3 回答
  • 0 关注
  • 162 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信