Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么put请求中的更新会覆盖Sequelize中的整个记录?_Javascript_Node.js_Reactjs_Request_Sequelize.js - Fatal编程技术网

Javascript 为什么put请求中的更新会覆盖Sequelize中的整个记录?

Javascript 为什么put请求中的更新会覆盖Sequelize中的整个记录?,javascript,node.js,reactjs,request,sequelize.js,Javascript,Node.js,Reactjs,Request,Sequelize.js,我正试着为我的项目制作一个“编辑”功能,我被这部分困住了 我有一个put请求: export const updateEvent = (event, id) => (dispatch, getState) => { request .put(`${baseUrl}/event/${id}`) .send(event) .then(response => { dispatch(updatedEvent(response.body))

我正试着为我的项目制作一个“编辑”功能,我被这部分困住了

我有一个put请求:

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)
  }


表单中保留为空的任何值都将以零(空字符串)覆盖我的字段。如何正确处理此问题?

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

在您的
路由器中。put()


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

在您的
路由器中。put()


大家好,欢迎来到StackOverflow!您应该提到您在问题中使用了Sequelize。漫不经心的人会以为你在使用MongoDB,否则的话。呜呜,我的错!谢谢你提到:)你好,欢迎来到StackOverflow!您应该提到您在问题中使用了Sequelize。漫不经心的人会以为你在使用MongoDB,否则的话。呜呜,我的错!谢谢你提到:)谢谢,这很有道理。我不知道为什么,但我以为PUT会自动为我做这件事。再次感谢:)谢谢,这是有道理的。我不知道为什么,但我以为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)
  }
})