MongoDB Node.js 驱动程序 4.0.0:Vercel 生产中的光标会话 ID 问题

将我的 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;
}
z442820293 回答:MongoDB Node.js 驱动程序 4.0.0:Vercel 生产中的光标会话 ID 问题

我遇到了同样的错误,但只是尝试使用变更流

collection.watch()

如果

changeStream.on('change',...

被使用了!

我的环境:

  • NodeJS v16.6.1
  • MongoDB 社区服务器 5.0.2
  • MongoDB 驱动程序 v4.1
  • ReplSet 2 个节点

mongod.conf:

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: 27017
  bindIp: 127.0.0.1,10.1.1.12

processManagement:
  timeZoneInfo: /usr/share/zoneinfo

security:
  authorization: enabled
  keyFile: /var/lib/mongodb-pki/keyfile

operationProfiling:
  mode: "slowOp"
  slowOpThresholdMs: 50

replication:
  replSetName: rs0

我的代码:

const { MongoClient } = require("mongodb"),user = encodeURIComponent(process.env.DB_USER),pass = encodeURIComponent(process.env.DB_PASS),host = process.env.DB_HOST,port = process.env.DB_PORT,uri = `mongodb://${user}:${pass}@${host}:${port}/?replicaSet=rs0`,options = { useNewUrlParser: true,useUnifiedTopology: true },client = new MongoClient(uri,options);
client.connect();
const db = client.db('flexograv'),collection = db.collection('jobs'),pipeline = [{ '$match': { 'operationType': 'insert' }}],changeStream = collection.watch(pipeline);
changeStream.on('change',change => {
    console.log({ change: change });
});
changeStream.on('error',error => {
    console.log({ error: `${error}` });
});

此连接导致错误:

"MongoServerError: Cursor session id (83bd3b49-cca9-4a9d-ab34-b8dc979b8010 - YtJ8CVGJPpojGlBhlVfpmkB+TWiGCwPUvkGEjp5tty0=) is not the same as the operation context's session id (none)"
本文链接:https://www.f2er.com/3392.html

大家都在问