zhanghj00 2019-06-27
主管前几天发现mongoDB已经升级到4.0了,迫不及待得让我实现他期待已久的事务回滚,发现还是有很多坑啊!
下面是我将已有的本地mongoDB升级到支持事务回滚的历程,分享出来,有错误的地方欢迎指正!
以mac为例哈
$ brew upgrade mongodb
$ npm i mongodb --save-dev
useNewUrlParser:true
,authSource:用户所在的db,一般为admin
const mongoClient = await MongoClient.connect(mongoClientUrl, { auth: { user: config.dbUserName, password: config.dbUserPassword, }, authSource:'admin', useNewUrlParser:true, });
$ mongod -dbpath ./db --port 27017 --replSet rs0
$ mongod -dbpath ./db_repl --port 27018 --replSet rs0
$ mongo $ rs.initiate() $ rs.add('localhost:27018');
export const getSession = async function() { return await state.mongoClient.startSession(); };
const session = await db.getSession(); session.startTransaction({ readConcern: {level: 'snapshot'}, writeConcern: {w: 'majority'}, });
db .collection(this.collecitonName) .insertOne(doc,{session});
await session.abortTransaction();
await session.commitTransaction();