CastError.在路径"_id "处,对于值"{ _id:':5ec5cc919efcf581eb692690'}"投向ObjectId失败。在路径"_id "处,模型 "Posts "的值"{ _id: ':5ec5cc919efcf581eb692690' }"投向ObjectId失败。

问题描述 投票:0回答:1

在服务器端检查路由器,它的控制台记录的数值是正确的,只是这里出现了如下错误。试图建立一个计数器,应该在后台更新值。但是我的问题是这个值不会被存储在那里。当使用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 })
    }
})
reactjs express redux router
1个回答
0
投票

你需要把补丁网址中的:删除,像这样。

axios.patch(`${API_URL}/${id}`

还有... findByIdAndUpdate 只需要_id的值,所以你只能传递这样的值。

await Post.findByIdAndUpdate(req.params.postId, ... 

findByIdAndUpdate(id, ...) 相当于 findOneAndUpdate({ _id: id }, ...).

© www.soinside.com 2019 - 2024. All rights reserved.