Advertisement
AviEzerzer

mongoDB conn service

Apr 17th, 2020
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const config = require('../config/index');
  2. const Logger = require('./logger.service');
  3. const ObjectId = require('mongodb').ObjectId;
  4.  
  5. var dbConn = null;
  6. var prmConn = null;
  7.  
  8. function connectToMongo() {
  9.     if (prmConn) return prmConn;
  10.     // Reuse existing connection if exist
  11.     if (dbConn) return Promise.resolve(dbConn);
  12.  
  13.     const MongoClient = require('mongodb').MongoClient;
  14.     const url = config.dbURL;
  15.  
  16.     prmConn = MongoClient.connect(url, { useNewUrlParser: true }).then((client) => {
  17.         Logger.info('[MONGO SERVICE] new connection to db');
  18.         prmConn = null;
  19.         // If we get disconnected (e.g. db is down)
  20.         client.on('close', () => {
  21.             Logger.info('[MONGO SERVICE] MongoDB Diconnected!');
  22.             dbConn = null;
  23.             client.close();
  24.         });
  25.         dbConn = client.db();
  26.         return dbConn;
  27.     });
  28.     return prmConn;
  29. }
  30.  
  31. module.exports = {
  32.     connect: connectToMongo,
  33.     ObjectId,
  34. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement