-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
45 lines (38 loc) · 1.25 KB
/
db.js
File metadata and controls
45 lines (38 loc) · 1.25 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
const mongoose = require("mongoose")
require("dotenv").config()
const MONGODB_URI = process.env.MONGODB_URI
//connect to mongoDB
function connectToMongoDB(){
mongoose.connect(MONGODB_URI)
mongoose.connection.on('connected', async ()=> {
console.log('Connected to MongoDB succesfully');
})
mongoose.connection.on('error', (err)=>{
console.log('Error connecting to the MongoDB', err);
})
}
module.exports = {connectToMongoDB}
const connectDB = async () => {
try {
let connect;
const options = {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
}
switch(process.env.NODE_ENV) {
case "development":
connect = await mongoose.connect(process.env.DEV_MONGO_URI, options);
break;
case "test":
connect = await mongoose.connect(process.env.TEST_MONGO_URI, options);
break;
default:
console.log("Connection did not succeed");
};
console.log(`connected to MongoDB in ${process.env.NODE_ENV} mode on ${connect.connection.host}`);
} catch (error) {
return error;
};
};