【问题标题】:MongoDB transactions implementationMongoDB事务实现
【发布时间】:2020-12-30 16:49:38
【问题描述】:

我得到了这段代码,使用 expressmongodb(mongoose) 将喜欢的动画存储在 db 中,用户可以点赞/不喜欢动画,所以我需要实现事务

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);
    }
});

我需要帮助来实现交易,我尝试过这种方式:

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);
    }
});

但它不起作用。 我还尝试在连接字符串中添加?replicaSet=rs?retryWrites=false 并安装

npm install run-rs -g

但都没有效果

【问题讨论】:

  • 这是一个GET操作,为什么需要一个事务?

标签: javascript node.js mongodb express mongoose


【解决方案1】:

尝试在会话之外发送响应。在await session.commitTransaction();之后 也试试这个问题的解决方案Mongodb v4.0 Transaction, MongoError: Transaction numbers are only allowed on a replica set member or mongos

如果您使用 Windows,请勿在连接字符串中使用 localhost 或 127.0.0.1 作为主机名,而是使用 计算机名 并在末尾添加 ?replicaSet=rsrs 是副本集的名称。

别忘了将&retryWrites=false 添加到您的连接字符串中。

使用run-rs -v 4.0.0 启动副本集。

【讨论】:

  • 我再次收到此错误:``` GET /animation-list/?username=marko 500 6.382 ms - 21 MongoError: Transaction numbers are allowed on a replica set member or mongos ```
  • 你连接到 mongodb Atlas 集群了吗?
  • 我在本地主机mongoose.connect('mongodb://localhost:27017/animationsdb');
  • 我编辑了我的答案。我上面发布的链接似乎有一个很好的解决方案。
  • 我也试过你现在发布的解决方案,但它对我不起作用
猜你喜欢
  • 2017-09-30
  • 1970-01-01
  • 2011-02-08
  • 1970-01-01
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多