Error Message: MongoError: bad auth Authentication failed through URI string

前端 未结 15 1733
终归单人心
终归单人心 2020-12-29 02:36

I\'m trying to connect to my mongoDB server via the connection string given to me by mongo:

"mongodb+srv://david:p         


        
相关标签:
15条回答
  • 2020-12-29 03:06

    I faced a similar issue, weirdly enough it got resolved when I created a new user in database access. This time though I clicked on autogenerate password. It should not matter but in my case it solved the issue.

    0 讨论(0)
  • 2020-12-29 03:07

    Are you writing your password in the place of <password>? If your aren't, a good practice is to create a environment variable on your operating system and call it using process.env.[your variable]. Ex:

    const password = process.env.YOURPASSWORDVARIABLE
    const db = 'mongodb+srv://david:'+password+'@cluster0-re3gq.mongodb.net/test?retryWrites=true'
    

    Better yet, you can also put your whole url connection string inside a env variable:

    0 讨论(0)
  • 2020-12-29 03:07

    Finally, it worked for me to used that connection string with a lower grade that NodeJs versions(2.2.12 or later) cluster url. And After that make sure you have to whitelist your current IP Address from Atlas MongoDB. It should display like 0.0.0.0/0 (includes your current IP address) in Network Access section in Atlas MongoDB. Connect to cluster NodeJs version 2.2.12 or later

    And the main issue was where I am storing that connection string url in a constant that part. So initially,I was storing that connection string value in single/double quote but every time I was getting Authentication failure error as it was unable to parse that "Password" value from Atlas mongoDB . So I used backtick (``)instead of single/double quote to store that connection string.

    Sample code where I am connecting mongoDB Atlas through a NodeJs application.

    const DB_USER = 'your username in atlas mongodb';
    
    const PASSWORD = encodeURIComponent('your password in atlas mongodb');
    
    const url = `mongodb://${DB_USER}:${PASSWORD}@cluster0-shard-00-00.3ytbz.mongodb.net:27017,cluster0-shard-00-01.3ytbz.mongodb.net:27017,cluster0-shard-00-02.3ytbz.mongodb.net:27017/sample-db?ssl=true&replicaSet=atlas-z26ao5-shard-0&authSource=admin&retryWrites=true&w=majority`;
    
    mongoose.connect(url,
      {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
        useFindAndModify: true
      })
      .then(() => {
        console.log('Connected to database !!');
      })
      .catch((err)=>{
        console.log('Connection failed !!'+ err.message);
      });
    
    0 讨论(0)
提交回复
热议问题