mongodb4.0支持事务
事务特性:
原子性:所有的改变都完成
一致性:最终执行结果一致就行
隔离性:一个事务的执行不能其它事务干扰。
持久性:指一个事务一旦提交,数据不会改变,存在数据库中
https://docs.mongodb.com/manual/core/transactions/
https://mongoosejs.com/docs/transactions.html
const session = await db.startSession();
session.startTransaction();
await Customer.create([{ name: 'Test' }], { session: session });
await Customer.findOne({ name: 'Test' }).session(session);
回滚:
await session.abortTransaction();
提交:
await session.commitTransaction();
结束事务:session.endSession();
参考:https://docs.mongodb.com/manual/core/transactions