简体   繁体   English

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

[英]Node rest API: put request is not updating the request data

Trying to update data using PUT request.尝试使用 PUT 请求更新数据。 But, the data is not updating and returning the previous data in postman.但是,数据不会更新并返回 postman 中的先前数据。

Postman put request: Postman 提出要求:

http://localhost:3000/api/actors/5daa8f1c5845ad0b5826b8d9?name=Tom

Postman response: 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
}

I have also tried to use findByIdAndUpdate.我也尝试过使用 findByIdAndUpdate。 Didn't get the result.没有得到结果。 Any help would be appreciated.任何帮助,将不胜感激。

Controller: 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:路由器:

router.put('/actors/:actorId', Actor.updateActor);

Your postman request is http://localhost:3000/api/actors/5daa8f1c5845ad0b5826b8d9?name=Tom so look like the data to update will be in req.query instead of req.body .您的 postman 请求是http://localhost:3000/api/actors/5daa8f1c5845ad0b5826b8d9?name=Tom所以看起来要更新的数据将在req.query而不是req.body中。

Note : You should put the data to update in the body instead of query like you're doing.注意:您应该将要更新的数据放在正文中,而不是像您正在做的那样查询。

More info here .更多信息在这里

Please use following code for getting update data 

 Actor.findOneAndUpdate({"_id":ObjectId(actorId)},data, 
 { new: true}).then((updatedData) => {
 res.send(updatedData);
 });

To resolve the ObjectId error use the below code.要解决 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM