简体   繁体   中英

MongoDb multi collection transactions do not work

I have to update two collections. I want to make sure that either both the collections get updated or they don't.

I created this simple example of two updates (both of them use same collection here, but they could be different):

       await this.client.connect();
    const session = this.client.startSession();

    try{
      const transactionOptions = {
        readPreference: 'primary',
        readConcern: { level: 'local' },
        writeConcern: { w: 'majority' }
    };

    await session.withTransaction(async () => {
    await this.client.db("Person").collection("persons").updateMany({ "phone":  "23138213"}, {$set: {"gender": "F10"} });
    await this.client.db("Person").collection("persons").updateMany({ "phone":  "23138213"},  "d");
  }, transactionOptions)
}
  finally{
    await session.endSession();

  }

Now if the initial value of gender was empty "" . Then after executing the above code, the final value should still be "" because the second update is invalid syntax and would throw exception.

But the result is gender:Male

Finally managed to solve it based on @D. SM's valuable comments.

    await this.client.connect();
    const session = this.client.startSession();

    try{
      const transactionOptions = {
        readPreference: 'primary',
        readConcern: { level: 'local' },
        writeConcern: { w: 'majority' }
    };
    await session.withTransaction(async () => {
    await this.client.db("Person").collection("persons").updateMany({ "phone":  "23138213"}, {$set: {"gender": "G2"} }, { session });
    await this.client.db("Person").collection("persons").updateMany({ "phone":  "23138213"},  "G2", { session });
  }, transactionOptions)
}
  finally{
    await session.endSession();
  }

Even after passing session to the updates, the transaction didn't seem to work. The issue was that I was supposed to wrap it within {}

await this.client.db("Person").collection("persons").updateMany({ "phone":  "23138213"}, {$set: {"gender": "G2"} }, { session });

Instead of

await this.client.db("Person").collection("persons").updateMany({ "phone":  "23138213"}, {$set: {"gender": "G2"} }, session );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM