While MongoDB does offer the ability to perform atomic updates using findOneAndUpdate
, it is limited to basic operations such as set or increment.
What I really need is a way to apply a custom function to transform my document:
const updateDoc = async (event) => {
const oldState = await db.collection(collectionName).findOne({ name });
const newState = customFunction(oldState, event);
await db.collection(collectionName).replaceOne({ name }, newState);
}
This function will be invoked by a system that does not wait for promises to resolve before continuing operation, resulting in potentially multiple synchronous calls.
Is there a method to modify updateDoc
to ensure atomicity so that when we execute:
updateDoc(event1); // without using await
updateDoc(event2);
We can guarantee that the stored document will reflect
customFunction(customFunction(initState, event1), event2)
?
Thank you