【问题标题】:How to fix 'setting true/false/value instead of null in mongodb using mongoose, nodejs and reactjs'如何使用 mongoose、nodejs 和 reactjs 在 mongodb 中修复“设置真/假/值而不是 null”
【发布时间】:2019-11-20 07:04:51
【问题描述】:

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

当我在邮递员或其他地方发出帖子请求时,它会很好地更新。

在 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.js reactjs mongodb mongoose http-post


    【解决方案1】:

    这段代码有很多问题,

    错误的数据采集:

    您正在发送{_id:id, update: {title: updated}
    这意味着在req.body 中会有两个键_idupdated 在您的路线中应该是(参考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 }))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      相关资源
      最近更新 更多