Right now we're using transaction as below:
exports.updateBalance = async (req, res) => {
let session = await mongoose.startSession({
readPreference: { mode: 'primary' },
readConcern: { level: 'snapshot' },
writeConcern: { w: 'majority' }
});
try {
await session.withTransaction(async () => {
let updateUser = await User.findOneAndUpdate(
{ _id: req.user._id },
{ $inc: {balance: req.body.amount} },
{ session }
)
let walletEntry = new UserWallet({
_userId: req.user._id,
amount: req.body.amount
})
await walletEntry.save({session})
})
} catch (error) {
await session.endSession();
}}
Now in above code we're saving document in UserWallet table. We have to pass session in save method. In this way transaction is working perfectly fine.
Now in our app there are many places where we are creating UserWallet entries. Now it is tough to manage because when we have to add any field, we have to make changes at all places where we are creating UserWallet entry.
So is there any way to create reusable function like createUserWalletEntry() in which we can pass required data and maintain transaction in controller and reusable function? It should also work when same user's data is getting updated in concurrent requests.