-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabaseConnection.js
More file actions
38 lines (34 loc) · 949 Bytes
/
Copy pathdatabaseConnection.js
File metadata and controls
38 lines (34 loc) · 949 Bytes
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
const mongoose = require('mongoose');
const { MongoMemoryServer } = require('mongodb-memory-server');
require('dotenv').config();
// connecting to the database using mongoDB
let mongoConnection = null;
const connectToDB = async () => {
try {
let dbUrl = process.env.DB_URI;
if (process.env.NODE_ENV === 'test') {
mongoConnection = await MongoMemoryServer.create();
dbUrl = mongoConnection.getUri();
}
const linked = await mongoose.connect(dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log(
`connected to MongoBD server with the host: ${linked.connection.host}`
);
} catch (err) {
console.log(err);
}
};
const disconnectToDB = async () => {
try {
await mongoose.connection.close();
if (mongoConnection) {
await mongoConnection.stop();
}
} catch (err) {
console.log(err);
}
};
module.exports = { connectToDB, disconnectToDB };