简体   繁体   English

无法使用 Mongoose 连接到 MongoDB

[英]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.我正在观看 MERN 堆栈上的此视频教程,但由于某些非常奇怪的原因,我无法连接到 MongoDB。 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.视频使用 mlab 为 MongoDB,它不再可用,所以我改为使用 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.我的密码没有任何特殊字符,我的IP地址在白名单中。 As for dbname , I have one database named "data" with a collection called "items," so I'm using "data" for dbname .至于dbname ,我有一个名为“data”的数据库和一个名为“items”的集合,所以我使用“data”作为dbname

The code in question that is causing my problem is in a file called server.js :导致我出现问题的相关代码位于名为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 .编辑:我认为添加另一个数据库访问帐户不会解决问题,因为MongoDB 上的管理员帐户具有读取和写入其数据库的能力 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 :这是我如何使用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这是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.您从“连接”按钮获得的 URI 字符串可能使用管理员帐户,即使这不是您要在 URI 字符串中使用的帐户,因此请记住这一点。 If you did that and you're still unable to connect, please use this checklist:如果您这样做了但仍然无法连接,请使用此清单:

数据库访问管理

网络访问管理

集群和集合

Try to add dbName in options:尝试在选项中添加dbName

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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