mschwartz
mschwartz

Reputation: 208

MongoDB Atlas very slow connection on hot reload

I have been working on a React application that would connect to MongoDB Atlas with Mongoose. Using nodemon and webpack for hot reloading it would reconnect to Mongo within milliseconds every time there was a reload. It was working nicely like this for months, then suddenly began taking 20+ seconds to connect on every reload - which has significantly increased dev time.

I cannot figure out what caused this to start happening and how to fix it. Any advice would be greatly appreciated.

Note: My IP Address has already been whitelisted.

const db = "mongodb+srv://<username>:<password>@cluster0-omitted.mongodb.net/<dbname>?retryWrites=true&w=majority"

const connectDB = async () => {
  try {
    console.log('Attempting to connect to MongoDB...');
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useCreateIndex: true,
      useFindAndModify: false,
      useUnifiedTopology: true,
    });
    console.log('MongoDB connected...');
  } catch (err) {
    console.log(err.message);
    process.exit(1); // Exit process with failure
  }
};

Upvotes: 7

Views: 6408

Answers (3)

Liger
Liger

Reputation: 191

I was having this same issue, MongoDB Compass taking 10+ seconds to connect, suddenly all my tests started to fail and hot reload while in local dev server was taking 10+ seconds..

I had recently moved to a new MacBook Pro M1 device, and my previous laptop was connecting almost instantly.

Eventually I figured out I was missing 8.8.8.8 in my network settings.

Mac System Preferences > Network > Wi-Fi > DNS

Upvotes: 11

DOOManiac
DOOManiac

Reputation: 6284

As ridiculous as it sounds, reboot your router. Or more technically, you have a problem with DNS and rebooting can resolve it.

I had a similar problem after a power failure at home. When the NAS came back not all Docker containers came back up, including my pihole. DNS seemed fine elsewhere so I didn't notice, but MongoDB Atlas specifically took 20 seconds to connect. After starting the Pihole docker container, it now connects in 600ms, which is much closer to normal.

Upvotes: 1

Atharva Malji
Atharva Malji

Reputation: 41

I don't know if this helps you out but have you tried to change IP allowed list to all and try it again. I had the same issue where I had assigned my network IP to allowed list. After changing it to allow all IP in MongoDB dashboard it seems to have solved the problem.

Upvotes: 0

Related Questions