title: MongoDB Node.js Driver 4.0.0: Cursor session id issues in production on Vercel
body: <p>Upgrading my Vercel-hosted app to the new MongoDB driver (4.0) has introduced sporadic errors like this:</p>
  <p><code>MongoServerError: Cursor session id ([session hash])is not the same as the operation context's session id (none)</code></p>
  <p>I have fiddled with the MongoDB caching and connection script as recommended by Vercel/Next <a href="https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/lib/mongodb.js" rel="nofollow noreferrer">https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/lib/mongodb.js</a> but the issue continues.</p>
  <p>I'm not clear enough on what the changes are in the new driver that might be introducing this, but it's fixed by rolling back to 3.6.10.</p>
  <p>The issue seems to happen when a request is made more than 30 seconds after an identical query from the same Node.js function.</p>
  <p>My db connection code:</p>
  <pre><code>import { MongoClient } from &quot;mongodb&quot;;
  
  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) =&gt; {
        return {
          client,
          db: client.db(dbName),
        };
      });
    }
    cached.conn = await cached.promise;
    return cached.conn;
  }
  </code></pre>
  <p><strong>Edit:</strong> This bug in the the v4 Node.js driver was <a href="https://github.com/mongodb/node-mongodb-native/releases/tag/v4.4.1" rel="nofollow noreferrer">fixed in 4.2.1</a></p>