首页 > 解决方案 > 尝试更新或删除帖子时出错

问题描述

我编写了一个代码,用于在 MongoDB 中发布和更新数据,用于删除数据,当我想在 mongoDB 中更新某些内容时,它会毫无问题地发布,但成功后我不能redirect

主要问题是更新部分,因为这根本不起作用,我只得到错误:

http://127.0.0.1:8080/update/undefined 404(未找到)

findByIdAndUpdate()在路线中使用,这是发布项目部分和更新项目的代码:

发布项目(路由器部分):

    router.post( "/", async( req, res, next ) => {
log.info(
    `Adding new car category - `,
    req.body,
    req.headers
)

try {
    let { title, author, description } = req.body;

    let avto = new Avto({
        title,
        author,
        description
    })

    await avto.save()

    return res.send( { success: true } )
} catch ( ex ) {
    log.error(
        `Error`,
        ex
    )
    return next( {
        msg: "Error while trying to save car category.",
        code: "CAR_SAVE_ERROR",
        status: 403
    } )
}
})

发布项目(/src/pages 部分):

    addCar = async() => {
    try {
        let addCar = await axios.post( 'http://127.0.0.1:8080/avto', {
            title: this.state.title,
            description: this.state.description,
            author: this.state.author
        })
        if ( addCar.data.success ) {
            console.log( "Car successfully added!" );
        }
    } catch ( err ) {
        console.log( err )
    }
    }

更新项目(路由器部分):

    router.put('/update/:id', async (req, res, next) => {
log.info(`Updating car `,
req.body,
req.headers)

try {
    Avto.findByIdAndUpdate(req.params.id,{$set:req.body}, {upsert:true}, function(err, avto){
        return res.send("Succesfully Updated!");
    })
} catch ( err ) {
    return next( {
        msg: "Error while trying update car.",
        code: "CAR_UPDATE_ERROR",
        status: 403
    })
}
} )

更新项目(/src/pages 部分):

    updateCar = async() => {
    try {
        let carId = this.props.match.params.id
        let updateCar = await axios.get( `http://127.0.0.1:8080/update/${carId}`, {
            id: this.state.id,
            title: this.state.title,
            description: this.state.description,
            author: this.state.author
        })
        if ( updateCar.data.success ) {
            console.log( "Car successfully updated!" );
        }
    } catch ( err ) {
        console.log( err )
    }
    }

我究竟做错了什么?我是 JS 的初学者。

标签: node.jsreactjsmongodb

解决方案


我认为保存部分有问题。它应该是这样的:

router.post( "/avto", async( req, res, next ) => {
log.info(
    'Adding new car category - ',
    req.body,
    req.headers
);

推荐阅读