mongodb4.0事务

在mongodb副本集中开启了事务 进行了两次写入插入操作,一次写入操作会成功,一次写入操作会失败,为什么数据依然会插入到数据库?
async insertStore() {

const { ctx } = this;
const query = ctx.request.body;
// Start a session.
const session = await this.ctx.app.mongoose.startSession({
  readPreference: { mode: 'primary' },
});
 // Start a transaction
  await session.startTransaction({
    readConcern: { level: 'snapshot' },
    writeConcern: { w: 'majority' },
  });
// Operations inside the transaction
try {

  await ctx.service.store.insertStore(query);
  const userRes = await this.findUser({ token: this.ctx.headers.token });
  const updateRes = await this.updateUser(
    { id: userRes[0].id },
    { $set: { store: 4343 } }
  );
  await session.commitTransaction();
} catch (err) {
  await session.abortTransaction();
  throw err;
} finally {
  await session.endSession();
}

}
mongoose配置 MongoDB shell version v4.0.10 mongoose v:5.6.x
mongoose: {

  client: {
    url: 'mongodb://127.0.0.1:27013,127.0.0.1:27012,127.0.0.1:27011/mall',
    options: {
      autoIndex: false,
      replicaSet: 'rs0',
      readPreference: 'secondary',
      w: 'majority',
    },
    // mongoose global plugins, expected a function or an array of function and options
    plugins: [],
  },
},
阅读 4.3k
1 个回答

加上配置项
const updateRes = await this.updateUser(

{ id: userRes[0].id },
{ $set: { store: 4343 } ,{session}}

);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进