简体   繁体   中英

Can't Connect to MongoDB using Mongoose

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.

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:password@cluster0-ipl5c.mongodb.net/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:

数据库访问管理

网络访问管理

集群和集合

Try to add dbName in options:

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

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