rplusg
rplusg

Reputation: 3446

Atomic transactions with nodejs and mongodb

I'm new to MEAN stack. please help with this situation.

My function has to do this and i want to make this threadsafe, i.e. i wanted to use this inside an API

1) query a collection and get a field from a document, say version.

2) Delete another document that matches with this version and other fields, in another DB.

3) insert new document in collection with new data, and version = version + 1

This would've been pretty simple in C# + Sql server world.

What is the best way to achieve this in node + mongodb environment?

Upvotes: 0

Views: 1071

Answers (1)

D. SM
D. SM

Reputation: 14480

MongoDB does not allow DDL in transactions:

The following operations are not allowed in transactions:

Operations that affect the database catalog, such as creating or dropping a collection or an index. For example, a transaction cannot include an insert operation that would result in the creation of a new collection.

You could:

  1. retrieve the version from collection
  2. generate an ObjectId to use for new data
  3. insert data, associating it with ObjectId generated in step 2
  4. update the collection in step 1 to have version = version + 1 and the ObjectId set to the one generated in step 2 using conditional update on version = original version; if the update doesn't match any documents restart from step 1
  5. remove old and orphan data

Subsequently, to query you'd need to obtain the ObjectId from the version and query by ObjectId.

No transactions are needed in this implementation.

Upvotes: 1

Related Questions