You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose已保存新Product,但接口返回“产品未创建”错误

问题排查与修复

核心原因:const变量被非法重新赋值

代码中用const声明了product变量,随后又执行product = await product.save();尝试对其重新赋值——const声明的变量不允许修改引用,这会直接抛出TypeError,触发catch块返回错误信息。但此时Mongoose的save()操作已完成(数据库写入成功),就出现了「数据存库但接口返回错误」的矛盾现象。

修复步骤

有两种可行的修复方式:

  1. 将const改为let,允许变量被重新赋值:
router.post('/', authenticateToken,isAdmin, async (req, res) => {
    try{
        const category = await Category.findById(req.body.category)
        if (!category) return res.status(400).send('Invalid Category')

        // 把const改为let,允许重新赋值
        let product = new Product({
            name: req.body.name,
            description: req.body.description,
            size: req.body.size,
            image: req.body.image,
            images: req.body.images,
            category: req.body.category,
            countInstock: req.body.countInstock,
            price: req.body.price,
            rating: req.body.rating,
            isFeatured: req.body.isFeatured,
            dateCreated: req.body.dateCreated,
        })
        product = await product.save();
        res.send(product)
    } catch(error){
        // 打印错误详情,方便后续排查
        console.error('创建产品出错:', error)
        return res.status(500).send("The product is not created")
    }
})
  1. 保持const声明,直接执行save无需重新赋值(Mongoose的save会自动更新原对象并返回保存后的文档):
router.post('/', authenticateToken,isAdmin, async (req, res) => {
    try{
        const category = await Category.findById(req.body.category)
        if (!category) return res.status(400).send('Invalid Category')

        const product = new Product({
            name: req.body.name,
            description: req.body.description,
            size: req.body.size,
            image: req.body.image,
            images: req.body.images,
            category: req.body.category,
            countInstock: req.body.countInstock,
            price: req.body.price,
            rating: req.body.rating,
            isFeatured: req.body.isFeatured,
            dateCreated: req.body.dateCreated,
        })
        await product.save();
        res.send(product)
    } catch(error){
        console.error('创建产品出错:', error)
        return res.status(500).send("The product is not created")
    }
})

额外建议

在catch块中添加错误日志打印,避免只返回模糊的错误信息,方便后续快速定位问题。

内容的提问来源于stack exchange,提问作者Mis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 19:22:36