NodeJS Mongoose 按官方文档实现事务触发超时错误是什么原因?
问题原因
1. 模型与连接绑定不匹配
你通过mongoose.model()注册的Customer模型默认绑定在Mongoose的全局默认连接上,但代码中你是单独调用mongoose.createConnection()创建了独立的新连接,事务会话是从这个新连接生成的,模型没有绑定到该连接,导致执行插入操作时模型找不到可用的数据库连接,触发缓冲超时报错。
2. 运行环境要求
MongoDB事务仅支持副本集、分片集群部署模式,本地默认启动的单节点MongoDB实例不支持事务功能,本地测试需要先将单节点配置为副本集模式。
修复方案
方案一:使用Mongoose全局连接
如果你不需要多连接隔离,直接用全局连接是最简单的写法:
const mongoose = require('mongoose'); const start = async () => { try { // 初始化全局连接 await mongoose.connect("mongodb://localhost:27017/transactions"); // 模型绑定全局连接 const Customer = mongoose.model('Customer', new mongoose.Schema({ firstName: { type: String } })); // 从全局连接创建会话 const session = await mongoose.startSession(); await session.withTransaction(async () => { await Customer.create([{ firstName: "peter" }], { session }); }); // 资源释放 await session.endSession(); await mongoose.disconnect(); } catch (error) { console.error(error); } }; start();
方案二:独立连接绑定模型
如果你确实需要使用createConnection创建独立连接,需要将模型绑定到该独立连接实例上:
const mongoose = require('mongoose'); const start = async () => { try { // 创建独立连接,注意要调用asPromise()等待连接就绪 const db = await mongoose.createConnection("mongodb://localhost:27017/transactions").asPromise(); // 将模型绑定到当前独立连接 const Customer = db.model('Customer', new mongoose.Schema({ firstName: { type: String } })); const session = await db.startSession(); await session.withTransaction(async () => { await Customer.create([{ firstName: "peter" }], { session }); }); // 资源释放 await session.endSession(); await db.close(); } catch (error) { console.error(error); } }; start();
注意事项
- 所有在事务中执行的数据库操作都必须传入同一个session实例,否则事务不会生效。
- 本地测试前请先将单节点MongoDB配置为副本集模式,否则事务功能无法正常运行。
内容的提问来源于stack exchange,提问作者swftowu69
相关产品推荐
相关产品推荐

