Repository navigation
Expand file tree
/
Copy pathdatabaseConnect.js
More file actions
57 lines (50 loc) · 1.43 KB
/
Copy pathdatabaseConnect.js
File metadata and controls
57 lines (50 loc) · 1.43 KB
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
require('dotenv').config();
const mongoose = require('mongoose');
const mongoConnectString = process.env.MONGO_URI;
if (!mongoConnectString) {
console.error('Missing MONGO_URI environment variable. Set it in a .env file (see .env.example).');
console.error('Process exited with code: 1');
process.exit(1);
}
function connect() {
mongoose.connect(mongoConnectString, {
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true,
useUnifiedTopology: true
});
const mongoDB = mongoose.connection;
mongoDB.on('error', (err) => {
console.error('MongoDB error: \n' + err);
throw err;
});
if (mongoDB.readyState === 2) {
mongoDB.once('connected', () => {
console.log('Connected to MongoDB!');
return true;
});
} else {
throw (new Error('Not connected to MongoDB'));
}
}
async function closeConnection() {
const mongoDB = mongoose.connection;
if (mongoDB.readyState === 1) {
mongoDB.close();
mongoDB.on('error', (err) => {
console.error('MongoDB error: ' + err);
throw err;
});
}
return mongoDB.once('disconnected', () => {
console.log('Disconnected from MongoDB!');
});
}
function getConnectionStatus() {
return mongoose.connection.readyState;
}
module.exports = {
connect,
closeConnection,
connectionStatus: getConnectionStatus,
};