Local Machine Implementation:
Transactions only work on replicate sets. So, the first step is to convert your standalone MongoDb instance to single replicate set.
- Shutdown MongoDB Server.
- Add below entry to mongod.cfg
replication:
replSetName: "rs0" - Start MongoDb Server.
- 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:
RUN echo "rs.initiate();" > /docker-entrypoint-initdb.d/replica-init.js
CMD ["--replSet", "rs0"]
2.1 Build the image
docker build -t custom-replica-mongo . -f mongo.dockerfile`
2.2 start the instance
docker run custom-replica-mongo
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:
For full example of transaction in MVC, you can refer below repository.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);
};
No comments:
Post a Comment