无法使用 Mongoose 连接到 MongoDB

我正在观看有关 MERN 堆栈的视频教程,但由于某些非常奇怪的原因,我无法连接到 MongoDB。这个问题让我很沮丧,因为我可能只是遗漏了一些非常基本的东西,所以如果答案对你来说很明显,请原谅我。

该视频使用 mlab for MongoDB,它不再可用,所以我改用 MongoDB Atlas。我应该用来将我的应用程序连接到数据库的密钥是:

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

我的密码没有任何特殊字符,我的IP地址在白名单中。至于dbname,我有一个名为“data”的数据库和一个名为“items”的集合,所以我使用“data”作为dbname.

导致我的问题的相关代码在一个名为的文件中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));

当我尝试运行服务器时,我不断收到此错误(我从一些路径中删除了我的名字):


{ 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:

有人可以帮我找出我做错了什么,以便我可以继续教程吗?感谢您的时间。



蛊毒传说
浏览 172回答 2
2回答

BIG阳

这是我如何使用的示例mongoose:const connectToMongo = async () => {&nbsp; try {&nbsp; &nbsp; await mongoose.connect(mongoUrl, { useNewUrlParser: true });&nbsp; &nbsp; console.log('connected to MongoDB');&nbsp; } catch(error) {&nbsp; &nbsp; console.log('error connection to MongoDB:', error.message);&nbsp; }};这是一个例子mongoUrl:mongo+srv://username:password@cluster0-ipl5c.mongodb.net/collectionname?retryWrites=true请确保您创建一个用户来读取和写入不是管理员帐户的数据库。您从“连接”按钮获得的 URI 字符串可能使用管理员帐户,即使这不是您想要在 URI 字符串中使用的帐户,因此请记住这一点。如果您这样做了但仍然无法连接,请使用此清单:检查正确的 IP 是否已列入白名单检查用户是否拥有正确的权限检查您是否使用了正确的数据库名称(集合)检查您的密码中是否有特殊字符(https://docs.atlas.mongodb.com/troubleshoot-connection/#special-pass-characters)

小怪兽爱吃肉

尝试添加dbName选项:await&nbsp;mongoose.connect('mongodb://root:example@mongo:27017',&nbsp;{&nbsp;dbName:&nbsp;"blog"&nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript