【问题标题】:exercise CRUD with Node.js Express et MongoDB使用 Node.js Express 和 MongoDB 练习 CRUD
【发布时间】:2021-08-27 07:35:52
【问题描述】:

我的代码:

/* ROUTE PUT update */
app.put('/api/products/:id', (req, res, next) => {
  productSchema.updateOne({ _id: req.params.id }, { ...req.body, _id: req.params.id })
    .then(() => res.status(200).json({ message: 'Modified!' }))
    .catch(error => res.status(400).json({ error }));
});

我的练习:PUT:/api/products/:id 将修改产品用 根据请求正文中发送的数据提供的 _id。这 请求正文的格式为:

{
    "name": string,
    "description": string,
    "price": number,
    "inStock": boolean
}

将返回表单的对象

{message: 'Modified!' }

我的 API 错误:使用 put 未正确更新带有 ID 的产品 路线!

【问题讨论】:

    标签: node.js mongodb express put


    【解决方案1】:

    update 对象中删除_id: req.params.id,并仅发送req.body。试试这个:

    app.put('/api/products/:id', (req, res, next) => {
      productSchema.updateOne({ _id: req.params.id }, req.body)
        .then(() => res.status(200).json({ message: 'Modified!' }))
        .catch(error => res.status(400).json({ error }));
    });
    

    【讨论】:

    • 谢谢我试试这个,但信息是一样的
    • 这只是一个位置问题,因为我首先放置了我的路线帖子,它给了我这个信息!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 2017-01-21
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    相关资源
    最近更新 更多