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

如何解决MongooseError:Model.prototype.save()不再接受回调的问题?

解决Mongoose Model.prototype.save() 不支持回调的错误

Mongoose 6.x及以上版本彻底移除了save()方法的回调参数支持,这就是触发该错误的原因。以下是两种符合当前Mongoose规范的修改方案:

方案1:使用async/await(推荐)

将路由处理函数声明为async,通过try/catch捕获保存过程中的错误:

const express = require('express')
const router = express.Router()
const Author = require('../models/author')

// All Authors Route
router.get('/', (req, res) => {
    res.render('authors/index')
})

// New Author Route
router.get('/new', (req, res) => {
    res.render('authors/new', {  author: new Author() })
})

// Create Author Route
router.post('/', async (req, res) => {
    const author = new Author({
        name: req.body.name
    })
    try {
        const newAuthor = await author.save()
        res.redirect('authors')
    } catch (err) {
        res.render('authors/new', {
            author: author,
            errorMessage: 'Error creating author'
        })
    }
})

module.exports = router

方案2:使用Promise.then()/catch()

如果不习惯async/await,也可以用Promise链式调用处理:

// Create Author Route
router.post('/', (req, res) => {
    const author = new Author({
        name: req.body.name
    })
    author.save()
        .then(newAuthor => {
            res.redirect('authors')
        })
        .catch(err => {
            res.render('authors/new', {
                author: author,
                errorMessage: 'Error creating author'
            })
        })
})

两种方案均适配当前Mongoose版本要求,可替代原有的回调写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:24:55