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?
steevej
(Steeve Juneau)
March 20, 2023, 10:11pm
2
Can you connect with Compass or mongosh?
Yes I can connect with Compass.
steevej
(Steeve Juneau)
March 21, 2023, 12:52am
4
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
Brock
(Brock)
March 24, 2023, 2:28am
5
See snippet code in link:
const mongoose = require('Mongoose');
mongoose.connect("MongoDB://localhost:<PortNumberHereDoubleCheckPort>/<DatabaseName>", {useNewUrlParser: true});
const <nameOfDbschemahere> = new mongoose.schema({
name: String,
rating: String,
quantity: Number,
someothervalue: String,
somevalue2: String,
});
const Fruit<Assuming as you call it FruitsDB> = mongoose.model("nameOfCollection" , <nameOfSchemeHere>);
const fruit = new Fruit<Because FruitsDB calling documents Fruit for this>({
name: …
I was using node v18 and opted in for v16.18.0 and it is working now.
2 Likes