1

I'm following this video tutorial on the MERN stack and I'm unable to connect to MongoDB for some very strange reason. This issue has been frustrating me quite a bit since I'm probably just missing something very basic, so please forgive me if the answer is painfully obvious to you.

The video uses mlab for MongoDB, which is no longer available, so I'm instead using MongoDB Atlas. The key I'm supposed to use to connect my application to the database is this:

mongodb+srv://<username>:<password>@fs-shopping-list.6rzkd.mongodb.net/<dbname>?retryWrites=true&w=majority

My password doesn't contain any special characters, and my IP address is on the whitelist. As for dbname, I have one database named "data" with a collection called "items," so I'm using "data" for dbname.

The code in question that is causing my problem is in a file called server.js:

const db = require('./config/keys').mongoURI; // I keep my key in a separate file in the way shown in the video

// Connect to MongoDB
mongoose
    .connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('MongoDB connected.'))
    .catch(err => console.log(err));

I keep getting this error when I try to run the server (I edited out my name from some of the paths):

{ MongooseServerSelectionError: bad auth Authentication failed.
    at NativeConnection.Connection.openUri (/fs_shopping_list/node_modules/mongoose/lib/connection.js:828:32)
    at Mongoose.connect (/fs_shopping_list/node_modules/mongoose/lib/index.js:335:15)
    at Object.<anonymous> (/fs_shopping_list/server.js:15:6)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
  message: 'bad auth Authentication failed.',
  reason:
   TopologyDescription {
     type: 'ReplicaSetNoPrimary',
     setName: null,
     maxSetVersion: null,
     maxElectionId: null,
     servers:
      Map {
        'fs-shopping-list-shard-00-01.6rzkd.mongodb.net:27017' => [ServerDescription],
        'fs-shopping-list-shard-00-02.6rzkd.mongodb.net:27017' => [ServerDescription],
        'fs-shopping-list-shard-00-00.6rzkd.mongodb.net:27017' => [ServerDescription] },
     stale: false,
     compatible: true,
     compatibilityError: null,
     logicalSessionTimeoutMinutes: null,
     heartbeatFrequencyMS: 10000,
     localThresholdMS: 15,
     commonWireVersion: null } }

Can someone please help me find out what I'm doing wrong so I can continue the tutorial? Thank you for your time.

EDIT: I don't think adding another account for database access will solve the problem, since admin accounts on MongoDB have the ability to read and write to their databases. The only thing I can think of that is possibly stopping me is maybe my Norton antivirus, although I'm not sure how to test this hypothesis.

8
  • 1
    If you are sure the URL is correct, do you maybe need to whitelist your IP? Commented Aug 12, 2020 at 21:20
  • Just to confirm, you are using a database specific username and password, not the username / password to your Atlas management account, right? Commented Aug 12, 2020 at 21:26
  • I am using the username and password for my Atlas account that I use to log in to the website and see my clusters. I'm not sure what else to use. Commented Aug 12, 2020 at 22:19
  • 1
    you need to use username and password of your database user which you have created under Security -> Database Access Commented Aug 13, 2020 at 0:34
  • It says that the role for my account is "atlasAdmin@admin." I am sure I'm using the correct password in the URI string, so something very strange is going on for the authentication to fail... Commented Aug 13, 2020 at 2:23

2 Answers 2

2

Here an example of how I do it with mongoose:

const connectToMongo = async () => {
  try {
    await mongoose.connect(mongoUrl, { useNewUrlParser: true });
    console.log('connected to MongoDB');
  } catch(error) {
    console.log('error connection to MongoDB:', error.message);
  }
};

Here is an example of the mongoUrl: mongo+srv://username:[email protected]/collectionname?retryWrites=true

Please make sure that you create a user to read and write to the database that isn't the admin account. The URI string you get from the "Connect" button might use the admin account even though that's not the account you want to use in the URI string, so keep that in mind. If you did that and you're still unable to connect, please use this checklist:

Database access management

Network access management

Clusters and collections

Sign up to request clarification or add additional context in comments.

5 Comments

I had clicked the "Add my current IP" button and "Allow access from anywhere" buttons on my cluster before I made this post :(. I think my problem has to do with the URI string I have, judging from what Matt Clark said.
Am I still able to use Mongoose after using MongoClient? I need to be able to use Mongoose's schemas, etc. to follow the tutorial.
Here I have used mongoose: github.com/MarianiGiacomo/Blog-App/tree/master/blog-app-be I hope it can help you. Under app.js I connect to the database. You can not see the dbUri in the repo, but it is in the form mongo+srv://username:[email protected]/collectionname?retryWrites=true
I have added some pictures. Hopefully they are helpful.
Okay I finally figured out what the problem was. I was copying the URI string provided when you click on the "Connect" button, and it kept saying to use my admin account. I created a new user that only has read-write privileges for the database, used that account in the URI instead, and now it finally works. MongoDB really should've made it clearer that the admin account apparently can't be used for reading and writing to the database (even though the documentation I've linked in the post suggests otherwise). Thank you so much for your help :)
0

Try to add dbName in options:

await mongoose.connect('mongodb://root:example@mongo:27017', { dbName: "blog" });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.