MongooseError问题:Model.create()不再支持回调函数,如何修复?
修复Mongoose中Model.create()不再支持回调函数的错误
问题背景
我用Express.js和Mongoose开发,之前运行正常的代码现在报错:
原代码:
M_User .create(data, (err) => { if (err) res.send({ kq: 0, msg: 'kết nối DB thất bại' }) res.send({ kq: 1, msg: 'Đã thêm thành công' }) })
报错信息:
throw new MongooseError('Model.create() no longer accepts a callback'); ^ MongooseError: Model.create() no longer accepts a callback at Function.create (C:\Users\ASUS\OneDrive\Máy tính\project-17-12\node_modules\mongoose\lib\model.js:2772:11) at C:\Users\ASUS\OneDrive\Máy tính\project-17-12\router\R_User.js:101:18 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
解决方案
Mongoose 6.x及以上版本移除了Model.create()对回调函数的支持,现在它返回一个Promise,你可以用以下两种方式修改代码:
方式1:使用async/await(推荐)
把路由处理函数声明为async,用try/catch捕获错误,同时避免重复发送响应:
// 示例路由处理函数 router.post('/your-path', async (req, res) => { try { const data = req.body; // 根据实际逻辑获取数据 await M_User.create(data); res.send({ kq: 1, msg: 'Đã thêm thành công' }); } catch (err) { res.send({ kq: 0, msg: 'kết nối DB thất bại' }); } });
方式2:使用Promise.then/catch
如果不习惯async/await,也可以用Promise链式调用:
M_User.create(data) .then(() => { res.send({ kq: 1, msg: 'Đã thêm thành công' }); }) .catch((err) => { res.send({ kq: 0, msg: 'kết nối DB thất bại' }); });
注意事项
- 原代码存在隐藏问题:错误分支的
res.send()后没有return,会导致后续的res.send()重复执行,引发Cannot set headers after they are sent to the client错误,上述两种修复方式已解决该问题。 - 该变化从Mongoose 6.x版本开始生效,确认你的项目依赖的Mongoose版本对应此规则。
内容的提问来源于stack exchange,提问作者Thu Hà Nguyễn
相关产品推荐
相关产品推荐

