首页 > 解决方案 > 如何使用 mongoose、nodejs 和 reactjs 在 mongodb 中修复“设置真/假/值而不是 null”

问题描述

我正在尝试使用 nodejs express 和 React 更新我的 MongoDB 数据库。但值不是更新,而是设置为空。

当我在邮递员或其他地方进行发布请求时,它会更新得很好。

在 expressjs 中

//@route UPDATE api/todos/:id
app.post("/api/todos/:id", (req, res) => {
  const { id } = req.params;
  Todo.findOne({ _id: id })
    .update({
      completed: req.body.completed
    })
    .then(res.json({ updated: true }))
    .catch(err => {
      if (err) throw err;
    });
});

在 Reactjs 中

//completed: true/false <- updated
axios.post(`api/todos/${id}`, {
  _id: id,
  update: { title: updated }
});

我试过 .patch 而不是 .post,但没有解决问题。

预期的结果应该是真/假,但它设置为空。

注意:它不仅适用于真/假值,而且适用于另一个值。

标签: node.jsreactjsmongodbmongoosehttp-post

解决方案


这段代码有很多问题,

错误的数据捕获:

您正在发送{_id:id, update: {title: updated}
这意味着req.body将有两个键_id,并且updated 在您的路线中应该是(参考Doc):

app.post("/api/todos/:id", (req, res) => {
  const { _id, updated } = req.params;
  Todo.update({ _id }, updated )
    .then(()=>res.json({ updated: true }))
    .catch(err => {
      if (err) throw err;
    });
});

错误的回调:

.then(res.json({ updated: true }))

这是错误的,因为then需要函数指针。function(){}

在你的情况下,res.json({ updated: true })()被调用是因为它认为res.json({ updated: true })是函数。

将其更改为:

.then(()=>res.json({ updated: true }))

推荐阅读