【问题标题】:How to update the status of order?如何更新订单状态?
【发布时间】:2021-05-06 09:46:56
【问题描述】:

我正在尝试创建电子商务网站。在哪个管理员更新订单状态。在某处我找到了逻辑,但我无法在邮递员中更新订单状态,也无法建立前台 为此结束。有人请帮忙解决这个问题吗?

exports.updateStatus = (req, res) => {  
    Order.updateOne(
       { _id: req.body.orderId },
       { set: { status: req.body.status } },
       { new: true },
       (err, order) => {
       if (err) {
           return res.status(400).json({error: "Cannot update order status"});
       }
       res.json(order);
    });
};

【问题讨论】:

  • 问题不清楚。您能否详细说明状态未更新是什么意思?你是如何测试这个 API 的?使用邮递员还是从 UI 调用它?在req.body 中是否正确传递了状态?此外,unable to build front end for that 是非常广泛的声明。
  • 我正在尝试使用邮递员更新状态,但它没有得到更新。
  • 您可以登录res.body 并确认是否正在设置状态吗?
  • 是.. 状态未更新
  • 你在 app.js 文件中使用过 express.json 中间件吗?如果你能分享 app.js 的代码,会有所帮助。

标签: node.js reactjs express mongoose


【解决方案1】:

基于 req.body 使用 req.body._id 而不是 req.body.orderId 并且不需要使用 set{new : true} 将返回修改后的文档而不是原始文档。 updateOne 没有这个选项。如果您需要更新文档的回复,请使用findOneAndUpdate

exports.updateStatus = (req, res) => {  
    Order.findOneAndUpdate(
       { _id: req.body._id},
        { status: req.body.status } ,
       { new: true },
       (err, order) => {
       if (err) {
           return res.status(400).json({error: "Cannot update order status"});
       }
       res.json(order);
    });
};

【讨论】:

  • 我用前端试试这个。它不起作用export const updateOrder = (orderId, userId, token, order) => { return fetch(${API}/order/update/${orderId}/${userId}, { method: "PUT", headers: { Accept: "application/json", Authorization: Bearer ${token}, }, body: JSON.stringify(order), }) .then((response) => { return response.json(); }) .catch((err) => console.log(err)); };
  • stackoverflow.com/questions/65804442/… 检查我对这个问题的回答,然后复制 javascript-fetch
【解决方案2】:

您正在尝试将{new: true} 选项与updateOne 方法一起使用。 此方法不支持此选项。

您应该使用支持{new: true}findOneAndUpdate 并返回更新后的文档(参见Docs)。

所以您的代码将如下所示:

exports.updateStatus = (req, res) => {  
    Order.findOneAndUpdate(
       { _id: req.body.orderId },
       { set: { status: req.body.status } },
       { new: true },
       (err, order) => {
       if (err) {
           return res.status(400).json({error: "Cannot update order status"});
       }
       res.json(order);
    });
};

【讨论】:

    猜你喜欢
    • 2017-07-18
    • 2014-09-06
    • 2017-07-16
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2011-06-04
    • 1970-01-01
    相关资源
    最近更新 更多