|
1 | 1 | import { MongoClient } from 'mongodb' |
2 | 2 |
|
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, |
16 | 7 | } |
17 | 8 |
|
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 |
24 | 11 |
|
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') |
27 | 14 | } |
28 | 15 |
|
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() |
32 | 22 | } |
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() |
49 | 28 | } |
| 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 |
0 commit comments