简体   繁体   中英

MongoDB transactions implementation

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

Try sending the response outside of your session. After await session.commitTransaction(); Also try out the solution from this question Mongodb v4.0 Transaction, MongoError: Transaction numbers are only allowed on a replica set member or mongos

Do NOT use localhost or 127.0.0.1 for the host name in your connection string if you use Windows, use computer name instead and add ?replicaSet=rs at the end. rs is the name of the replica set.

Also don't forget to add &retryWrites=false to your connection string.

Use run-rs -v 4.0.0 to start a replica set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM