index.js 943 B

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