title: How to do an atomic custom update of a mongodb document?
body: <p>I am aware that MongoDB can do atomic updates using <code>findOneAndModify</code> but this only permits basic operations like set or increment.</p>
  
  <p>What I need is to apply a custom function to transform my document:</p>
  
  <pre><code>const updateDoc = async (event) =&gt; {
    const oldState = await db.collection(collectionName).findOne({ name });
    const newState = customFunction(oldState, event);
    await db.collection(collectionName).replaceOne({ name }, newState);
  }
  </code></pre>
  
  <p>This function will be called by a system that won't wait for a resolved promise to continue working: there can be multiple synchronous calls.</p>
  
  <p>Is there a way to rewrite <code>updateDoc</code> to make it atomic, so that when we do:</p>
  
  <pre><code>updateDoc(event1); // note the absence of await
  updateDoc(event2);
  </code></pre>
  
  <p>We can be sure that the stored doc will be <code>customFunction(customFunction(initState, event1), event2)</code>?</p>
  
  <p>Thanks</p>