在服务器端检查路由器,它的控制台记录的数值是正确的,只是这里出现了如下错误。试图建立一个计数器,应该在后台更新值。但是我的问题是这个值不会被存储在那里。当使用Postman时,该值将被成功存储。有什么办法可以解决这个问题。
export const incrementProduct = (index, updateAmount, id) => {
return dispatch => {
dispatch(increment(index));
try {
axios.patch(`${API_URL}/:${id}`, {
amount: updateAmount
}).then(res => {
console.log(res.config);
})
} catch(err) {
console.log(err)
}
}
}
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
amount: {
type: Number,
required: true
},
editable: {
type: Boolean,
required: true
},
data: {
type: Date,
default: Date.now
}
});
// update
router.patch('/:postId', async(req, res) => {
console.log('update', req.params.postId + 'amount ' + req.body.amount)
try {
const updatedPost = await Post.findByIdAndUpdate(
{_id: req.params.postId}, <--- this cause the console error...
{$set:
{
amount: req.body.amount
},
})
console.log('try')
res.json(updatedPost)
} catch(err) {
console.log(err + 'test ')
res.json({ message: err })
}
})
你需要把补丁网址中的:删除,像这样。
axios.patch(`${API_URL}/${id}`
还有... findByIdAndUpdate 只需要_id的值,所以你只能传递这样的值。
await Post.findByIdAndUpdate(req.params.postId, ...
findByIdAndUpdate(id, ...)
相当于 findOneAndUpdate({ _id: id }, ...)
.