-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmongoose.js
50 lines (40 loc) · 1.16 KB
/
mongoose.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
const mongoose = require("mongoose");
const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
throw new Error("MONGODB_URI is not defined in .env");
}
/**
* 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.mongo;
if (!cached) {
cached = global.mongo = { conn: null, promise: null };
}
const connectToDatabase = async () => {
console.log("Connecting to MongoDB...");
// Connect to cached connection if available
if (cached.conn) {
console.log("Cached MongoDB Connected successfully");
return cached.conn;
}
// Connect to MongoDB
if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
cached.promise = mongoose.connect(MONGODB_URI, opts);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", function () {
console.log("MongoDB Connected successfully");
});
}
cached.conn = await cached.promise;
return cached.conn;
};
module.exports = {
connectToDatabase,
};