Skip to content

Instantly share code, notes, and snippets.

@benjamingr
Created December 14, 2020 14:13
Show Gist options
  • Save benjamingr/43014ac85ac9f0e67b6a66227fa9a30e to your computer and use it in GitHub Desktop.
Save benjamingr/43014ac85ac9f0e67b6a66227fa9a30e to your computer and use it in GitHub Desktop.

Revisions

  1. benjamingr created this gist Dec 14, 2020.
    17 changes: 17 additions & 0 deletions mongo.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    // Let's say I have transaction code that looks like:

    let state = 1;
    session.withTransaction(async () => {
    // this can retry, which means otherFn can run twice and possible insert the wrong value or in the wrong order
    state++;
    await Promise.all([
    coll1.insertOne({ abc: 1 }, { session });
    otherFn(state, session),
    ])
    });

    async function otherFn(state, session) {
    // get some data from redis or another DB
    await setTimeout(Math.random() * 100);
    await coll2.insertOne({abc: state});
    }