Sunday, February 7, 2021

Transactions With Mongoose & NodeJs, Express

Local Machine Implementation:

Transactions only work on replicate sets. So, the first step is to convert your standalone MongoDb instance to single replicate set. 

  1. Shutdown MongoDB Server.
  2. Add below entry to mongod.cfg
    replication:
      replSetName: "rs0"
  3. Start MongoDb Server.
  4. Initiate the replica set from within the mongo shell using command "rs.initiate()".

After converting to replicate set, we can work on the NodeJs code.


Docker Implementation:

1.Create a dockerfile: mongo.dockerfile
FROM mongo
RUN echo "rs.initiate();" > /docker-entrypoint-initdb.d/replica-init.js
CMD ["--replSet", "rs0"]

2. Installation:
2.1 Build the image
docker build -t custom-replica-mongo . -f mongo.dockerfile`
2.2 start the instance
docker run custom-replica-mongo

3. Create with docker-compose
version: '3'
services:
  mongo:
    image: custom-replica-mongo
    build:
      context: .
      dockerfile: mongo.dockerfile
    ports:
     - 27017:27017


Create a model: 

const StudentModel= mongoose.model('StudentModel', new mongoose.Schema({

  year: { type: Number },

  standard: { type: Number },

}));

Example of saving a document using transaction:

const createStudent = async (req, res, next) => {

    const { year, standard } = req.body;


    const session = await StudentModel.startSession();

    session.startTransaction();


    const newStudent = new StudentModel({

      id: uuidv4(),

      year: year,

      standard: standard,

    })

  

    try {

      const opts = { session };

      await newStudent.save(opts);


      // commit the changes if everything was successful

      await session.commitTransaction();

      session.endSession();

    } catch (err) {

      // If an error occurred, abort the whole transaction and

      // undo any changes that might have happened

      await session.abortTransaction();

      session.endSession();


      const error = new Error(' Creating document failed.');

      return next(error);

    }

  

    res.status(201).json(newStudent);

};

For full example of transaction in MVC, you can refer below repository.

The example included updating, delete in transaction.

References:
https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set/

No comments:

Post a Comment