Skip to content

Commit 220fa9c

Browse files
kukicadoleerobijjk
authoredAug 25, 2021
Update to use the latest MongoDB best practices to limit connection pooling issues. (#28350)
* Update to use the latest MongoDB best practices. * lint-fix Co-authored-by: Lee Robinson <me@leerob.io> Co-authored-by: jj@jjsweb.site <jj@jjsweb.site>
1 parent 877f982 commit 220fa9c

File tree

4 files changed

+34
-47
lines changed

4 files changed

+34
-47
lines changed
 
+1-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
MONGODB_URI=
2-
MONGODB_DB=
1+
MONGODB_URI=

‎examples/with-mongodb/README.md

+2-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ If you want to learn more about MongoDB, visit the following pages:
1111

1212
Once you have access to the environment variables you'll need, deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
1313

14-
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-mongodb&project-name=with-mongodb&repository-name=with-mongodb&env=MONGODB_URI,MONGODB_DB&envDescription=Required%20to%20connect%20the%20app%20with%20MongoDB)
14+
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-mongodb&project-name=with-mongodb&repository-name=with-mongodb&env=MONGODB_URI&envDescription=Required%20to%20connect%20the%20app%20with%20MongoDB)
1515

1616
## How to use
1717

@@ -40,7 +40,6 @@ cp .env.local.example .env.local
4040
Set each variable on `.env.local`:
4141

4242
- `MONGODB_URI` - Your MongoDB connection string. If you are using [MongoDB Atlas](https://mongodb.com/atlas) you can find this by clicking the "Connect" button for your cluster.
43-
- `MONGODB_DB` - The name of the MongoDB database you want to use.
4443

4544
### Run Next.js in development mode
4645

@@ -56,7 +55,7 @@ yarn dev
5655

5756
Your app should be up and running on [http://localhost:3000](http://localhost:3000)! If it doesn't work, post on [GitHub discussions](https://github.com/vercel/next.js/discussions).
5857

59-
You will either see a message stating "You are connected to MongoDB" or "You are NOT connected to MongoDB". Ensure that you have provided the correct `MONGODB_URI` and `MONGODB_DB` environment variables.
58+
You will either see a message stating "You are connected to MongoDB" or "You are NOT connected to MongoDB". Ensure that you have provided the correct `MONGODB_URI` environment variable.
6059

6160
When you are successfully connected, you can refer to the [MongoDB Node.js Driver docs](https://mongodb.github.io/node-mongodb-native/3.4/tutorials/collections/) for further instructions on how to query your database.
6261

‎examples/with-mongodb/lib/mongodb.js

+23-40
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,32 @@
11
import { MongoClient } from 'mongodb'
22

3-
const MONGODB_URI = process.env.MONGODB_URI
4-
const MONGODB_DB = process.env.MONGODB_DB
5-
6-
if (!MONGODB_URI) {
7-
throw new Error(
8-
'Please define the MONGODB_URI environment variable inside .env.local'
9-
)
10-
}
11-
12-
if (!MONGODB_DB) {
13-
throw new Error(
14-
'Please define the MONGODB_DB environment variable inside .env.local'
15-
)
3+
const uri = process.env.MONGODB_URI
4+
const options = {
5+
useUnifiedTopology: true,
6+
useNewUrlParser: true,
167
}
178

18-
/**
19-
* Global is used here to maintain a cached connection across hot reloads
20-
* in development. This prevents connections growing exponentially
21-
* during API Route usage.
22-
*/
23-
let cached = global.mongo
9+
let client
10+
let clientPromise
2411

25-
if (!cached) {
26-
cached = global.mongo = { conn: null, promise: null }
12+
if (!process.env.MONGODB_URI) {
13+
throw new Error('Please add your Mongo URI to .env.local')
2714
}
2815

29-
export async function connectToDatabase() {
30-
if (cached.conn) {
31-
return cached.conn
16+
if (process.env.NODE_ENV === 'development') {
17+
// In development mode, use a global variable so that the value
18+
// is preserved across module reloads caused by HMR (Hot Module Replacement).
19+
if (!global._mongoClientPromise) {
20+
client = new MongoClient(uri, options)
21+
global._mongoClientPromise = client.connect()
3222
}
33-
34-
if (!cached.promise) {
35-
const opts = {
36-
useNewUrlParser: true,
37-
useUnifiedTopology: true,
38-
}
39-
40-
cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
41-
return {
42-
client,
43-
db: client.db(MONGODB_DB),
44-
}
45-
})
46-
}
47-
cached.conn = await cached.promise
48-
return cached.conn
23+
clientPromise = global._mongoClientPromise
24+
} else {
25+
// In production mode, it's best to not use a global variable.
26+
client = new MongoClient(uri, options)
27+
clientPromise = client.connect()
4928
}
29+
30+
// Export a module-scoped MongoClient promise. By doing this in a
31+
// separate module, the client can be shared across functions.
32+
export default clientPromise

‎examples/with-mongodb/pages/index.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import Head from 'next/head'
2-
import { connectToDatabase } from '../lib/mongodb'
2+
import clientPromise from '../lib/mongodb'
33

44
export default function Home({ isConnected }) {
55
return (
@@ -223,7 +223,13 @@ export default function Home({ isConnected }) {
223223
}
224224

225225
export async function getServerSideProps(context) {
226-
const { client } = await connectToDatabase()
226+
const client = await clientPromise
227+
228+
// client.db() will be the default database passed in the MONGODB_URI
229+
// You can change the database by calling the client.db() function and specifying a database like:
230+
// const db = client.db("myDatabase");
231+
// Then you can execute queries against your database like so:
232+
// db.find({}) or any of the MongoDB Node Driver commands
227233

228234
const isConnected = await client.isConnected()
229235

0 commit comments

Comments
 (0)
Please sign in to comment.