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

如何重构代码解决Model.prototype.save()不再支持回调的问题

解决Mongoose save()不支持回调的重构方案

Mongoose 6.x及后续版本已移除Model.prototype.save()的回调参数支持,必须改用Promise风格(async/await 或 .then()/.catch())处理异步操作。以下是针对你代码的重构步骤:

1. 修复并重构新增数据模块

原saveProduct函数存在参数冗余问题,且未利用Promise,修改为:

module.exports.saveProduct = function(productInstance){
    // 实例的save()返回Promise,直接返回即可
    return productInstance.save();
}

注意:new Product()创建的实例已包含数据,无需再向save()传入data参数。

2. 重构路由处理逻辑

使用async/await简化异步代码并添加错误处理:

router.post('/insert', async (req,res)=>{
    try {
        let product = new Product({
            name:req.body.name,
            price:req.body.price,
            image:req.body.image,
            description:req.body.description
        });
        await Product.saveProduct(product);
        res.redirect('/');
    } catch (err) {
        console.error(err);
        // 可选:给前端返回错误响应
        res.status(500).send('产品保存失败');
    }
})

如果你更习惯链式调用风格,也可以用.then()实现:

router.post('/insert', (req,res)=>{
    let product = new Product({
        name:req.body.name,
        price:req.body.price,
        image:req.body.image,
        description:req.body.description
    });
    Product.saveProduct(product)
        .then(() => res.redirect('/'))
        .catch(err => {
            console.error(err);
            res.status(500).send('产品保存失败');
        });
})

可选:简化数据库连接代码

新版本Mongoose中useNewUrlParser和useUnifiedTopology已默认启用,可简化连接代码:

const dbUrl = 'mongodb://127.0.0.1:27017/productDB';
mongoose.connect(dbUrl)
    .then(() => console.log('数据库连接成功'))
    .catch(err => console.error('数据库连接失败:', err));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:05:05