Unverified Commit e0da6a60 authored by Valeri Karpov's avatar Valeri Karpov Committed by GitHub

cache Mongoose connections between hot reloads (#23321)



## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.

## Documentation / Examples

- [ ] Make sure the linting passes - No, I get hundreds of unrelated errors like:
```
build/babel/plugins/next-page-config.ts(8,28): error TS2307: Cannot find module 'next/types'.
build/entries.ts(11,32): error TS2307: Cannot find module '@next/env'.
build/index.ts(1,31): error TS2307: Cannot find module '@next/env'.
build/index.ts(9,10): error TS2305: Module '"next/dist/compiled/nanoid/index.cjs"' has no exported member 'nanoid'.
```

Re: https://github.com/Automattic/mongoose/issues/9987, the current Mongoose example doesn't do a good job of persisting state between hot reloads. Not sure why Lambda doesn't keep the same `import mongoose` between reloads, but it doesn't seem to. This approach lines up more closely with [Mongoose's Lambda docs](https://mongoosejs.com/docs/lambda.html) and the existing `with-mongodb` example.
parent 6eabef68
......@@ -6,9 +6,9 @@ This example shows how you can use a MongoDB database to support your Next.js ap
## Deploy your own
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](#step-2-set-up-environment-variables), 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-mongoose&project-name=with-mongodb-mongoose&repository-name=with-mongodb-mongoose)
[![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-mongoose&project-name=with-mongodb-mongoose&repository-name=with-mongodb-mongoose&env=MONGODB_URI&envDescription=Required%20to%20connect%20the%20app%20with%20MongoDB&envLink=https://github.com/vercel/next.js/tree/canary/examples/with-mongodb-mongoose%23step-2-set-up-environment-variables)
## How to use
......@@ -20,16 +20,6 @@ npx create-next-app --example with-mongodb-mongoose with-mongodb-mongoose-app
yarn create next-app --example with-mongodb-mongoose with-mongodb-mongoose-app
```
## Install and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
## Configuration
### Step 1. Get the connection string of your MongoDB server
......@@ -66,6 +56,20 @@ yarn install
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).
## Deploy on Vercel
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
You can deploy this app to the cloud with [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
#### Deploy Your Local Project
To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [import to Vercel](https://vercel.com/import/git?utm_source=github&utm_medium=readme&utm_campaign=next-example).
**Important**: When you import your project on Vercel, make sure to click on **Environment Variables** and set them to match your `.env.local` file.
#### Deploy from Our Template
Alternatively, you can deploy using our template by clicking on the Deploy button below.
[![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-mongoose&project-name=with-mongodb-mongoose&repository-name=with-mongodb-mongoose&env=MONGODB_URI&envDescription=Required%20to%20connect%20the%20app%20with%20MongoDB&envLink=https://github.com/vercel/next.js/tree/canary/examples/with-mongodb-mongoose%23step-2-set-up-environment-variables)
import mongoose from 'mongoose'
const { MONGODB_URI } = process.env
if (!MONGODB_URI) {
throw new Error(
'Please define the MONGODB_URI environment variable inside .env.local'
)
}
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached = global.mongoose
if (!cached) {
cached = global.mongoose = { conn: null, promise: null }
}
async function dbConnect() {
// check if we have a connection to the database or if it's currently
// connecting or disconnecting (readyState 1, 2 and 3)
if (mongoose.connection.readyState >= 1) {
return
if (cached.conn) {
return cached.conn
}
return mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
})
if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
bufferCommands: false,
bufferMaxEntries: 0,
useFindAndModify: false,
useCreateIndex: true,
}
cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
return mongoose
})
}
cached.conn = await cached.promise
return cached.conn
}
export default dbConnect
{
"env": {
"MONGODB_URI": "@next_example_mongodb_uri"
},
"build": {
"env": {
"MONGODB_URI": "@next_example_mongodb_uri"
}
}
}
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