In mongodb is it possible to create a transaction of 2 queries? Like find and update separately?

Viewed 365

I use mongodb (with mongoose) and I have a case where I find a document, run a bunch of complicated conditional checks and then update the document.

This is fine but now I want to ensure that the document I'm updating in the end hasn't been updated by a different update query while my conditions have been running.

Can I create a lock or somehow contain all these actions within a transaction?

1 Answers

You add a simple field editor and make sure each process has ownership of the document when it's time to update.

Here is a simple example:

let processId = uniqueID;

//if doc is none then a different process 'owns' it. need to decide on behaviour.
let doc = await collection.findOneAndUpdate({_id: docId, editor: {$exists: false}}, {$set: {editor: processId}})

### do calculations. ###

let newValue = calculatedValue;
let newDoc = await collection.findOneAndUpdate({_id: docId, editor: processId}, {$unset: {editor: ""}})

I feel that using transactions as suggjested in the comments is an overkill, from the docs:

In MongoDB, an operation on a single document is atomic

And

For situations that require atomicity of reads and writes to multiple documents , MongoDB supports multi-document transactions.

Transactions are meant for more complex situations than this, and I feel this overhead is not needed as a simple solution suffices.

Related