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

前端 未结 15 1921
终归单人心
终归单人心 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: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);
      });
    

提交回复
热议问题