Cant connect to mongo via mongoose

I am simply trying to connect to mongodb atlas via node.js with Mongoose but get the following error:
“MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you’re trying to access the database from an IP that isn’t whitelisted.”

I have whitelisted 0.0.0.0/0 and also set my actual IP too locally.

I find this happens frequently when i setup a new cluster.

I am running a stand alone script.

const mongoose = require('mongoose');
const intialDbConnection = async () => {
  try {
    await mongoose.connect("mongodb+srv://testuser:testpassword@cluster0.v51itw1.mongodb.net/?retryWrites=true&w=majority", {
      useNewUrlParser: true,
      useUnifiedTopology: true
    })
    console.log("db connected")
    
  }
  catch (error) {
    console.error(error);
  }
}

intialDbConnection()
.then(() => console.log('connected'))

Why can’t I connect?

Can you connect with Compass or mongosh?

Yes I can connect with Compass.

Then try with a older or newer version of mongoose and/or node.

The fact that you can connect with Compass, confirms that your cluster is okay, that your firewall/vpn is okay.

3 Likes

See snippet code in link:

I was using node v18 and opted in for v16.18.0 and it is working now.

2 Likes

Thank you this fixed it.