简体   繁体   中英

Cannot connect by mongoDB Atlas URI using mongoose in node

I am trying to connect my atlas cluster URI in my node project Node version: 12.4.1 mongoose: 5.2.7

this is how my URL looks alike

mongoose.connect(mongodb+srv://usernane:pass@uri/db_name?authSource=db_name&w=1, {
        useCreateIndex: true,
        keepAlive: 1,
        useNewUrlParser: true,
        useFindAndModify: false,
        useUnifiedTopology: true
    });

I am facing error authentication failed, What I am doing wrong any help will be appreciated.

The format and/or query parameters of the connection string you've provided for MongoDB Atlas looks incorrect. Please ensure, the format is as follows:

mongodb+srv://<username>:<password>@<cluster-id>.mongodb.net/<db-name>?retryWrites=true&w=majority

(The above is taken from MongoDB Atlas connection example)

If, after the above correction - you still face auth issues, I suggest checking with details and possibly create a test user from your Atlas dashboard - docs on authentication .

First things first, i prefer to await the connect method, to handle any possible errors. So something like:

try {
  await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: 
  true});
} catch (error) {
  handleError(error);
}

Secondly, if password contains special characters, they should be URL encoded. You can use this tool: https://www.urlencoder.org/

Finally, in my case, i did not know i had to allow my current ip address to mongoDB atlas. While in atlas:

  1. click on your cluster then on the left side
  2. under security click Network access
  3. on the right click ADD IP ADDRESS.

This should fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM