I got this code that uses express and mongodb(mongoose) to store liked animations in db, the user has the ability to like/dislike animations so I need to implement transactions:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const User = require('./login').User;
mongoose.connect('mongodb://localhost:27017/animationsdb');
router.get('/', async(req, res) => {
// implement transaction
try {
const result = await User.findOne({ username: req.query.username });
if (result) {
console.log("Liked animations:", result.likedAnimations);
res.send({ animationList: result.likedAnimations });
} else {
console.log("no database result found");
res.sendStatus(404);
}
} catch (e) {
console.log(e);
res.sendStatus(500);
}
});
I need help imlementing the transactions, I tried this way:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const User = require('./login').User;
mongoose.connect('mongodb://localhost:27017/animationsdb');
router.get('/', async(req, res) => {
// implement transactions
try {
const session = await mongoose.startSession();
session.startTransaction();
const result = await User.findOne({ username: req.query.username }).session(session);
if (result) {
console.log("Liked animations:", result.likedAnimations);
res.send({ animationList: result.likedAnimations });
} else {
console.log("no database result found");
res.sendStatus(404);
}
await session.commitTransaction();
session.endSession();
} catch (e) {
console.log(e);
res.sendStatus(500);
}
});
But it does'nt work.
Also I tried adding ?replicaSet=rs
in connection string and ?retryWrites=false
and installing
npm install run-rs -g
but none of it worked