summaryrefslogtreecommitdiff
path: root/src/connectDb.js
blob: c7ad13b57bb35b5873819d766a640c9a41558da0 (plain)
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
const mongoose = require('mongoose');
const Promise = require('bluebird');

const MONGODB_URL = process.env.MONGODB_URI || 'mongodb://localhost:27017/bsu-fantom';
const { MONGODB_USER, MONGODB_PASSWORD } = process.env;

let connection;

const connectDb = () => new Promise ((resolve, reject) => {
  mongoose.Promise = Promise;

  mongoose.connect(MONGODB_URL, {
    user: MONGODB_USER,
    pass: MONGODB_PASSWORD,
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false,
    family: 4 // Use IPv4, skip trying IPv6
  });

  connection = mongoose.connection;

  connection.on('error', error => {
    console.log(error);
    reject(error);
  });

  connection.once('open', () => {
    console.log('Connection to MongoDB successfull')
    resolve();
  });
});

const getConnection = () => connection;

module.exports = {
  connectDb,
  getConnection
};