我有一个名为item
的对象:
我还有一个 PUT 请求,该请求应该能够更改 item
内的一些值。有些值在对象内部,有些则不在对象内部。一个例子是我需要能够更改 settings
对象内部的值。目前我的 PUT 请求如下所示:
export function updateSettings(id, item) {
return dispatch => {
axios
.put(`${settings.hostname}/cookie/${id}`, item)
.then(res => {
dispatch({
type: 'COOKIES_UPDATED',
payload: {
item
}
})
})
.catch(err => console.log(err))
}
}
当记录 res.data
时,我只得到这个:
_id: "598960d891202556389cxd"
后端进程处理 PUT 请求的方式如下:
r.put('/cookies' + '/:id', async (ctx, next) => {
console.log(key)
await ctx.db
.replaceOne({ _id: objectId(ctx.params.id) }, ctx.request.body)
ctx.body = { _id: ctx.params.id }
console.log(ctx.request.body)
})
我正在使用 Redux 表单提交我的输入字段,我的 onSubmit
如下所示:
onSubmit={handleSubmit(props => {
// props is the updated form values
onSubmit(id, props)
})}
这会将新值发送到服务器并更新数据库,但它也会扰乱我的 item
对象的结构。一些字段被删除,所以我得到了使用 diff
的提示。Diff
( https://github.com/srcagency/object-diff ) 的目的是仅在更改到服务器时发送,但是就我而言,它不会更新任何内容。 Item
看起来完全一样。
所以这是我的问题,我不知道如何更新我的 item
对象中的特定字段。如果需要,我可以发送更多代码。
感谢您的阅读!
最佳答案
router.route('/cookies/:id')
.put(function(req, res) {
Items.findById(req.params.id, function(err, item) {
if (err)
res.send(err);
// if you want update all settings object
item.settings = req.body;
// if something on settings field, item.settings.field1 = req.body.field1
item.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Your item updated!' });
});
});
});
关于javascript - 更新数据库对象中的特定字段 | Axios、Redux 形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45563822/