index.js 1.0 KB

123456789101112131415161718192021222324252627282930
  1. /**
  2. * Created by Syed Afzal
  3. */
  4. const mongoose = require('mongoose');
  5. const {log} = require('../utils/helpers/logger');
  6. exports.connect = (app) => {
  7. const options = {
  8. useNewUrlParser: true,
  9. autoIndex: false, // Don't build indexes
  10. reconnectTries: 30, // Retry up to 30 times
  11. reconnectInterval: 500, // Reconnect every 500ms
  12. poolSize: 10, // Maintain up to 10 socket connections
  13. // If not connected, return errors immediately rather than waiting for reconnect
  14. bufferMaxEntries: 0
  15. }
  16. const connectWithRetry = () => {
  17. mongoose.Promise = global.Promise;
  18. console.log('MongoDB connection with retry')
  19. mongoose.connect(process.env.MONGODB_URI, options).then(()=>{
  20. console.log('MongoDB is connected');
  21. app.emit('ready');
  22. }).catch(err=>{
  23. console.log('MongoDB connection unsuccessful, retry after 2 seconds.')
  24. setTimeout(connectWithRetry, 2000)
  25. })
  26. }
  27. connectWithRetry();
  28. };