Unverified Commit 220fa9cd authored by Ado Kukic's avatar Ado Kukic Committed by GitHub

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: 's avatarLee Robinson <me@leerob.io>
Co-authored-by: 's avatarjj@jjsweb.site <jj@jjsweb.site>
parent 877f9829
MONGODB_URI= MONGODB_URI=
MONGODB_DB=
\ No newline at end of file
...@@ -11,7 +11,7 @@ If you want to learn more about MongoDB, visit the following pages: ...@@ -11,7 +11,7 @@ If you want to learn more about MongoDB, visit the following pages:
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): 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):
[![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) [![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)
## How to use ## How to use
...@@ -40,7 +40,6 @@ cp .env.local.example .env.local ...@@ -40,7 +40,6 @@ cp .env.local.example .env.local
Set each variable on `.env.local`: Set each variable on `.env.local`:
- `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. - `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.
- `MONGODB_DB` - The name of the MongoDB database you want to use.
### Run Next.js in development mode ### Run Next.js in development mode
...@@ -56,7 +55,7 @@ yarn dev ...@@ -56,7 +55,7 @@ yarn dev
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). 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).
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. 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.
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. 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.
......
import { MongoClient } from 'mongodb' import { MongoClient } from 'mongodb'
const MONGODB_URI = process.env.MONGODB_URI const uri = process.env.MONGODB_URI
const MONGODB_DB = process.env.MONGODB_DB const options = {
useUnifiedTopology: true,
if (!MONGODB_URI) { useNewUrlParser: true,
throw new Error(
'Please define the MONGODB_URI environment variable inside .env.local'
)
}
if (!MONGODB_DB) {
throw new Error(
'Please define the MONGODB_DB environment variable inside .env.local'
)
} }
/** let client
* Global is used here to maintain a cached connection across hot reloads let clientPromise
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached = global.mongo
if (!cached) { if (!process.env.MONGODB_URI) {
cached = global.mongo = { conn: null, promise: null } throw new Error('Please add your Mongo URI to .env.local')
} }
export async function connectToDatabase() { if (process.env.NODE_ENV === 'development') {
if (cached.conn) { // In development mode, use a global variable so that the value
return cached.conn // is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
} }
clientPromise = global._mongoClientPromise
if (!cached.promise) { } else {
const opts = { // In production mode, it's best to not use a global variable.
useNewUrlParser: true, client = new MongoClient(uri, options)
useUnifiedTopology: true, clientPromise = client.connect()
}
cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
return {
client,
db: client.db(MONGODB_DB),
}
})
}
cached.conn = await cached.promise
return cached.conn
} }
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise
import Head from 'next/head' import Head from 'next/head'
import { connectToDatabase } from '../lib/mongodb' import clientPromise from '../lib/mongodb'
export default function Home({ isConnected }) { export default function Home({ isConnected }) {
return ( return (
...@@ -223,7 +223,13 @@ export default function Home({ isConnected }) { ...@@ -223,7 +223,13 @@ export default function Home({ isConnected }) {
} }
export async function getServerSideProps(context) { export async function getServerSideProps(context) {
const { client } = await connectToDatabase() const client = await clientPromise
// client.db() will be the default database passed in the MONGODB_URI
// You can change the database by calling the client.db() function and specifying a database like:
// const db = client.db("myDatabase");
// Then you can execute queries against your database like so:
// db.find({}) or any of the MongoDB Node Driver commands
const isConnected = await client.isConnected() const isConnected = await client.isConnected()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment