将我的 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;
}