-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongodb.js
52 lines (45 loc) · 1.22 KB
/
mongodb.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const path = require("path");
require("dotenv").config({
path: path.join(__dirname, ".env.local"),
});
const { MongoClient, MongoError } = require("mongodb");
const { MONGODB_URI, MONGODB_DB } = process.env;
if (!MONGODB_URI) {
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"
);
}
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentiatlly
* during API Route usage.
*/
let cached = global.mongo;
if (!cached) cached = global.mongo = {};
async function connectToDatabase() {
if (cached.conn) return cached.conn;
if (!cached.promise) {
const conn = {};
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
cached.promise = MongoClient.connect(MONGODB_URI, opts)
.then((client) => {
conn.client = client;
return client.db(MONGODB_DB);
})
.then((db) => {
conn.db = db;
cached.conn = conn;
});
}
await cached.promise;
return cached.conn;
}
module.exports = { connectToDatabase };