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: [],
  },
},
2019-07-06 提问
1 个回答
0

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

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

);

撰写答案

推广链接