Javascript 为什么put请求中的更新会覆盖Sequelize中的整个记录?
我正试着为我的项目制作一个“编辑”功能,我被这部分困住了 我有一个put请求: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))
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)
}
})