Skip to content
Advertisement

Not able to connect MongoDB Atlas with Node.js trough Mongoose

I’m trying to connect a Node.js application with MongoDB Atlas trough Mongoose and I’m getting 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. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
    at NativeConnection.Connection.openUri (C:UsersmarinDownloadsProject part2Project part2docker_appnode_modulesmongooselibconnection.js:797:32)
    at C:UsersmarinDownloadsProject part2Project part2docker_appnode_modulesmongooselibindex.js:332:10
    at C:UsersmarinDownloadsProject part2Project part2docker_appnode_modulesmongooselibhelperspromiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:UsersmarinDownloadsProject part2Project part2docker_appnode_modulesmongooselibhelperspromiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (C:UsersmarinDownloadsProject part2Project part2docker_appnode_modulesmongooselibindex.js:1153:10)     
    at Mongoose.connect (C:UsersmarinDownloadsProject part2Project part2docker_appnode_modulesmongooselibindex.js:331:20)
    at connectDb (C:UsersmarinDownloadsProject part2Project part2docker_appsrcconnection.js:9:6)
    at Server.<anonymous> (C:UsersmarinDownloadsProject part2Project part2docker_appserver.js:27:3)
    at Object.onceWrapper (events.js:519:28) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'cluster0.huaic.mongodb.net:27017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}

My code is:

const mongoose = require("mongoose");
const User = require("./User.model");

const connection = '"mongodb://cluster0.huaic.mongodb.net/myFirstDatabase"';

const connectDb = () => {
  return mongoose
    .connect(connection)
    .then((res) => {
      return res;
    })
    .catch((error) => {
      console.log(error);
    });
};

module.exports = connectDb;

I’ve allowed access from every IP on mongodb atlas and when I try to connect directly to atlas everything works fine.

Advertisement

Answer

For first, you have double quotes in the connection variable. Secondly: it seems to me that mongoUri should include the username and password in the query string, right?

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement