Skip to content

Commit

Permalink
chore(docs): Update mongodb code example for mongo singleton (#10683)
Browse files Browse the repository at this point in the history
Co-authored-by: Nico Domino <yo@ndo.dev>
  • Loading branch information
fsocietystudios and ndom91 committed Apr 28, 2024
1 parent af902db commit dca0f22
Showing 1 changed file with 23 additions and 13 deletions.
36 changes: 23 additions & 13 deletions docs/pages/getting-started/adapters/mongodb.mdx
Expand Up @@ -79,33 +79,43 @@ The MongoDB adapter does not handle connections automatically, so you will have

```ts filename="lib/db.ts"
// This approach is taken from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
import { MongoClient } from "mongodb"
import { MongoClient, ServerApiVersion } from "mongodb";

if (!process.env.MONGODB_URI) {
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"')
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"');
}

const uri = process.env.MONGODB_URI
const options = {}
const uri = process.env.MONGODB_URI;
const options = {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
};

let client
let clientPromise: Promise<MongoClient>
let client;
let clientPromise: Promise<MongoClient>;

if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
let globalWithMongo = global as typeof globalThis & {
_mongoClientPromise?: Promise<MongoClient>;
};

if (!globalWithMongo._mongoClientPromise) {
client = new MongoClient(uri, options);
globalWithMongo._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise
clientPromise = globalWithMongo._mongoClientPromise;
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
clientPromise = client.connect()
client = new MongoClient(uri, options);
clientPromise = client.connect();
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise
export default clientPromise;
```

0 comments on commit dca0f22

Please sign in to comment.