【问题标题】:MongoDB Node.js Driver 4.0.0: Cursor session id issues in production on VercelMongoDB Node.js 驱动程序 4.0.0:Vercel 生产中的光标会话 id 问题
【发布时间】:2021-10-06 23:03:23
【问题描述】:

将我的 Vercel 托管应用升级到新的 MongoDB 驱动程序 (4.0) 引入了如下零星错误:

MongoServerError: Cursor session id ([session hash])is not the same as the operation context's session id (none)

我已经按照 Vercel/Next https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/lib/mongodb.js 的建议修改了 MongoDB 缓存和连接脚本,但问题仍然存在。

我不太清楚可能引入此问题的新驱动程序有哪些变化,但已通过回滚到 3.6.10 来解决。

当来自同一个 Node.js 函数的相同查询后超过 30 秒发出请求时,似乎会出现此问题。

我的数据库连接代码:

import { MongoClient } from "mongodb";

let uri = process.env.MONGODB_URI;
let dbName = process.env.MONGODB_DB;

let cached = global.mongo;

if (!cached) {
  cached = global.mongo = { conn: null, promise: null };
}

export async function connectToDatabase() {
  if (cached.conn) {
    return cached.conn;
  }

  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    };

    cached.promise = MongoClient.connect(uri, opts).then((client) => {
      return {
        client,
        db: client.db(dbName),
      };
    });
  }
  cached.conn = await cached.promise;
  return cached.conn;
}

编辑:这是 Node 驱动程序 V4 中的错误,仍未解决

【问题讨论】:

  • 你运行的是什么版本的节点? 4.0只支持12+
  • 在 Vercel 上运行节点 14。
  • 您好@DBNZ 有您对错误的引用或我可以关注的内容以了解何时修复错误。
  • 我想我们谈谈他的错误:jira.mongodb.org/browse/NODE-1420

标签: node.js mongodb aws-lambda next.js vercel


【解决方案1】:

collection.find() 与大型集合一起使用时,我遇到了同样的错误,并且在我将其更改为collection.find().limit(100) 后它消失了 - 仅供您参考。

【讨论】:

    【解决方案2】:

    我们最近也遇到了这个错误,另一个帮助我们的潜在解决方法是将会话显式传递给查询。它也写在corresponding ticket中。例如,如果你使用.find,那么你可以有这样的东西:

    const session = mongoClient.startSession();
    try {
      const query = await collection.find({}, { session });
    } finally {
      await session.endSession();
    }
    

    【讨论】:

    • 这个问题的真正解决方案
    猜你喜欢
    • 1970-01-01
    • 2020-05-02
    • 2023-03-20
    • 1970-01-01
    • 2016-10-18
    • 2016-08-03
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多