[Mongoose] Transactions vs Fawn (Two Phase Commits)

This took a while to understand. Here is what I found:

Transactions cannot be done on a standalone mongod instance (this is exactly what we have if you are following along with the course). We must convert our standalone instance of our database into a replica set. In my opinion, the easiest way to do this is using the mongod command with the --replSet arg option. First, you must edit your mongod config file. This file is found in your bin folder within your MongoDB directory (Generally file is located under this path: C:\Program Files\MongoDB\Server\6.0\bin\mongod.cfg). To edit this file, I recommend notepad++.

mongod.cfg edit:

Within the mongod.cfg file, look for #replication. Add the following lines to end up with:

#replication:
oplogSizeMB: 2000
replSetName: vidlyRep

The two lines following #replication may require indentation (not sure on this).
Note: you can use any name you want for your replica set. I used vidlyRep (feel free to change this). Save the file and you are ready to go.

Now, from the CLI, use the command: mongod --replSet vidlyRep. That’s it. We can now use transactions.

One of the posts above uses the withTransaction() method. This is a cleaner and more maintainable approach to what I ended up with (I was messing around with this for a while and finally landed on code that seems to function appropriately). However, the code above does not include the { session } parameter. This is a critically important parameter to pass to your methods which are updating, creating, etc. a document in your database. My understanding is that the { session } parameter will tie the executed line of code back to the session. Then, if at any point something goes wrong (i.e. exception, error, etc.), the session will abort and rollback all activities tied to it (i.e. those where the { session } parameter was passed). My code does not use this withTransaction() helper method, but rather the traditional approach (i.e. start/abort/end session manually). Here is the code:

4 Likes