Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 节点rest API:put请求未更新请求数据_Javascript_Node.js_Express_Mongoose - Fatal编程技术网

Javascript 节点rest API:put请求未更新请求数据

Javascript 节点rest API:put请求未更新请求数据,javascript,node.js,express,mongoose,Javascript,Node.js,Express,Mongoose,正在尝试使用PUT请求更新数据。但是,数据并没有更新和返回postman中以前的数据 邮递员寄出要求: http://localhost:3000/api/actors/5daa8f1c5845ad0b5826b8d9?name=Tom 邮递员回应: { "createdAt": "2019-10-19T04:16:13.317Z", "updatedAt": "2019-10-19T04:16:13.317Z", "_id": "5daa8f1c5845ad0b582

正在尝试使用PUT请求更新数据。但是,数据并没有更新和返回postman中以前的数据

邮递员寄出要求:

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);

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

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


更多信息。

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

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

响应代码是200。但是,数据库中的数据并没有更新。数据库连接也很好。因为,我可以获取、删除数据。谢谢。响应代码是200。但是,数据库中的数据没有更新。请现在检查const{ObjectId}=require('mongodb');添加该行我尝试了以下操作:Actor.findOneAndUpdate({“\u id”:mongoose.Types.ObjectId(actorId)},data,{new:true});而且,这是有效的。在解决ObjectId之前,我们需要添加mongoose.Types。我有个问题。问题是:如果我想使用req.body发送数据,那么过程是什么?对于邮递员,您可以将数据放在body部分,如下所示:明白了。我试过x-url编码。因此,通过查询更新数据不是一个好的选择。
Please use following code for getting update data 

 Actor.findOneAndUpdate({"_id":ObjectId(actorId)},data, 
 { new: true}).then((updatedData) => {
 res.send(updatedData);
 });
var mongoose = require('mongoose');
const updateActor = await Actor.findOneAndUpdate({"_id":mongoose.Types.ObjectId(actorId)},data, { new: true });
res.send(updateActor);