-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
64 lines (47 loc) · 1.57 KB
/
db.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
53
54
55
56
57
58
59
60
61
62
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import url from 'url';
// ESM AppRoot
const appRoot = url.fileURLToPath(import.meta.url).split('db.js')[0];
const getENV = () =>
process.env?.NODE_ENV?.trim()?.toLowerCase() === 'production'
? '.env'
: '.dev.env';
// Load Config
dotenv.config({ path: `${appRoot}/.config.env` });
// Load Secrets
dotenv.config({ path: `${appRoot}/${getENV()}` });
const connectDB = async () => {
const { MONGO_URI } = process.env;
const MONGO_OPTIONS = { };
mongoose.set('strictQuery', true);
const conn = await mongoose.connect(MONGO_URI, MONGO_OPTIONS);
// Connect to MongoDB
mongoose.connection.on('connecting', () => {
console.log('Connecting to MongoDB…');
});
mongoose.connection.on('error', (error) => {
console.error('MongoDB Connection Error: ', error);
mongoose.disconnect();
});
mongoose.connection.on('connected', () =>
console.log(`MongoDB Connected ${mongoose.connection.host}`)
);
mongoose.connection.once('open', () => {
console.log('MongoDB Connection Opened');
});
mongoose.connection.on('reconnected', () => {
console.log(`MongoDB Reconnected ${mongoose.connection.host}`);
});
mongoose.connection.on('disconnected', () => {
console.warn('MongoDB Disconnected');
mongoose.connect(MONGO_URI, MONGO_OPTIONS);
});
if (!conn || !conn.connection || !conn.connection.host) {
console.error('MongoDB Connection FAILURE');
return false;
}
console.log(`MongoDB Connected: ${conn.connection.host}`);
return conn;
};
export default connectDB;