使用 Node.js Express 和 MongoDB 练习 CRUD

问题描述 投票:0回答:2

我的代码:

/* 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
2个回答
0
投票

_id: req.params.id
对象中删除
update
,并仅发送
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 }));
});

0
投票

您的代码将搜索具有唯一参数 id 而不是 a 的产品。具有给定供应商 ID 的产品。一种解决方案是在产品架构中有一个字段 seller_id,然后在查询中使用该字段,如下所示

 app.put('/api/products/:id', (req, res, next) => {
  productSchema.updateOne({ supplier_id: req.params.id }, req.body)
    .then(() => res.status(200).json({ message: 'Modified!' }))
    .catch(error => res.status(400).json({ error }));
});
© www.soinside.com 2019 - 2024. All rights reserved.