Skip to content Skip to sidebar Skip to footer

Using `mongoose Transactions` When Saving Message In Two Collections In Mongodb

If the student sends a message to the teacher, the message is saved in the teachers and students collections. The same situation is when a teacher sends a message to the student, t

Solution 1:

I have added in the code Anytime there is an error:

await session.abortTransaction();

Otherwise (happy path) commit the changes.

await session.commitTransaction();

Abort and commit are Promise base functions, so I have changed the functions where they were used as async.

const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();

//const app = express();// Connect to our Database and handle an bad connectionsmodule.exports.db = mongoose
    .createConnection(process.env.DATABASE, { 
        useNewUrlParser: true, 
        useFindAndModify: false,
        useUnifiedTopology: true, 
        useCreateIndex: true
    }
);




//controllerconst db = require('./connection');



module.exports.sendMessage = async (req, res) => {
    
    const session = await db.startSession();
    session.startTransaction();

    let {sender, receiver, msg, role} = req.body;
    var hex = /[0-9A-Fa-f]{6}/g;

    sender = (hex.test(sender))? mongoose.Types.ObjectId(sender) : sender;
    receiver = (hex.test(receiver))? mongoose.Types.ObjectId(receiver) : receiver;
    console.log(sender, receiver, msg, 'send');

            if(role === 'tutor') {
                let teacherMessage =  newTeacherMessageSchema.TeacherMessageSchema({
                    contentInfo : {
                        msg : msg
                    },
                    sender : sender
                })

                let studentMessage =  newTeacherMessageSchema.TeacherMessageSchema({
                    contentInfo : {
                        msg : msg
                    },
                    receiver : receiver
                })
        
                db.db.collection('teachers').findOneAndUpdate( 
                    { _id : receiver },
                    { $push: { messages: teacherMessage } },
                    async (err, updated) => {
                        console.log(updated, 'vvv');
        
                        updated.value.hashed_password = undefined;
                        updated.value.salt = undefined;
        
                        if(err) {
                            await session.abortTransaction();
                            res.status(404).json(err);
                            return
                        }
        
                        if (updated) {
                            res.status(200).json(updated.value);

                            db.db.collection('students').findOneAndUpdate( 
                                { _id : sender },
                                { $push: { messages: studentMessage } },
                               
                            );
                        }
                    }, session(session)
                )
        
              
            }
        
        
            if(role === 'student') {
                let studentMessage =  newStudentMessageSchema.StudentMessageSchema({
                    contentInfo : {
                        msg : msg
                    },
                    receiver : receiver
                })

                let teacherMessage =  newTeacherMessageSchema.TeacherMessageSchema({
                    contentInfo : {
                        msg : msg
                    },
                    sender : sender
                })
        
               
        
                db.db.collection('students').findOneAndUpdate( 
                    { _id : sender },
                    { $push: { messages: studentMessage } },
                    async (err, updated) => {
                        console.log(updated, 'sss');
            
                        updated.value.hashed_password = undefined;
                        updated.value.salt = undefined;
            
                        if(err) {
                            await session.abortTransaction();
                            res.status(404).json(err);
                            return;
                        }
            
                        if (updated) {
                            res.json(updated.value);
                            db.db.collection('teachers').findOneAndUpdate( 
                                { _id : receiver },
                                { $push: { messages: teacherMessage } },
                               
                            )
                        }
                    }, 
                    session(session)
                )
            }

            await session.commitTransaction();
}

Post a Comment for "Using `mongoose Transactions` When Saving Message In Two Collections In Mongodb"