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



我正试图为我的项目制作一个"编辑"功能,但我被困在了这一部分。。

我有一个看跌请求:

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

这是上述看跌期权的路线,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)
}

表单中任何留空的值都将不使用任何内容(空字符串(覆盖我的字段。如何正确处理此问题?

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

在您的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)
}
})

最新更新