【问题标题】:Why does my update in a put request overwrite the whole record in Sequelize?为什么我在 put 请求中的更新会覆盖 Sequelize 中的整个记录​​?
【发布时间】:2020-06-25 06:34:53
【问题描述】:

我正在尝试为我的项目制作“编辑”功能,但我被困在这部分..

我有一个放置请求:

export const updateEvent = (event, id) => (dispatch, getState) => {
  request
    .put(`${baseUrl}/event/${id}`)
    .send(event)
    .then(response => {
      dispatch(updatedEvent(response.body))
    })
    .catch(error => console.log(error))
}

这是上述 put 的路径,Sequelize 为 ORM:

router.put('/event/:id', async (req, res, next) => {
  const { id } = req.params
  try {
    const event = await Event.findByPk(id)
    const updatedEvent = await event.update(req.body)
    res.send(updatedEvent)
  } catch (error) {
    next(error)
  }
})

当我用邮递员测试它时,一切都按预期工作。我遇到问题的地方是当我从前端的 React 发送 put 数据时。

我有一个表单,我将我的数据保存在本地状态,然后将其分派到这样的操作:

  handleSubmit = e => {
    e.preventDefault()
    const id = this.props.event.id
    const updatedEvent = {
      name: this.state.name,
      description: this.state.description,
      picture: this.state.picture,
      startDate: this.state.startDate,
      endDate: this.state.endDate,
      userId: this.props.userId
    }

    this.props.updateEvent(updatedEvent, id)
  }

表单中任何留空的值都会用任何内容(空字符串)覆盖我的字段。我该如何正确处理?

【问题讨论】:

  • 您好,欢迎来到 StackOverflow!您应该提到您在问题中使用 Sequelize。不专心的人只会假设您正在使用 MongoDB。
  • 糟糕,我的错!感谢您提及:)

标签: javascript node.js reactjs request sequelize.js


【解决方案1】:

一种解决方案是过滤您的对象,以便您删除任何具有空值的属性,因此不会包含在数据库更新中。

在你的router.put()

router.put('/event/:id', async (req, res, next) => {
  const { id } = req.params
  try {
    const event = await Event.findByPk(id);

    // filter req.body to remove empty values
    const { body } = req;
    const filteredBody = Object.keys(body).reduce((resultObj, key) => {
      if(body[key] != ''){
        resultObj[key] = body[key];
      }
      return resultObj;
    }, {});

    const updatedEvent = await event.update(filteredBody);
    res.send(updatedEvent)
  } catch (error) {
    next(error)
  }
})

【讨论】:

  • 谢谢,这很有道理。我不知道为什么,但我认为 PUT 会自动为我执行此操作。再次感谢您:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
  • 2019-05-20
  • 2013-01-17
相关资源
最近更新 更多