无法使用mongoose连接到mongoDB Atlas:{MongoNetworkError:无法连接到服务器}

时间:2020-01-26 14:38:19

标签: node.js mongodb express mongoose

尽管我不是第一个不能使用猫鼬连接到mongoDB地图集的Stackoverflow,但似乎没有人出现我的特定错误:

{MongoNetworkError:无法连接到服务器 [cluster0-shard-00-00-shqnc.mongodb.net:27017]在第一次连接时 [MongoNetworkError:连接5至 cluster0-shard-00-00-shqnc.mongodb.net:27017已关闭]

这是我的服务器设置方式:

Keys.js

module.exports = {
  mongoURI:
    "mongodb+srv://Ahmed:<MyMongoDBAtlasPWD>@cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority"
};  

Server.js

const express = require("express");
const mongoose = require("mongoose");
const app = express();

// DB Config
const db = require("./config/keys").mongoURI;

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

app.get("/", (req, res) => {
  res.send("Hello");
});

//process.env.Port is for Heroku
const port = process.env.Port || 5000;
// `` ES6 Template literal is used so that we can put a variable inside the String
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});  

这是MongoDB地图集网站建议使用的代码:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://Ahmed:<password>@cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});

但是,由于我不想使用mongoClient而是使用mongoose,所以遇到了一些麻烦,而且我看不出为什么代码不起作用;

编辑1:我已经设法使用Shell命令进行连接(签出我的答案)。但是,通过应用程序进行连接无法正常工作,并且会显示其他错误:

{MongoNetworkError:无法连接到服务器 [cluster0-shard-00-01-shqnc.mongodb.net:27017]在第一次连接时 [MongoError:错误的身份验证失败。]

编辑2:我犯了一个愚蠢的错误。我忘了从中删除<>。现在一切都很好。

2 个答案:

答案 0 :(得分:2)

问题是我试图使用我的MongoDB Atlas帐户密码而不是用户密码进行连接。是的,那是两件事。
1。点击数据库访问
enter image description here

2。编辑当前用户并修改密码 enter image description here

3。使用该密码连接到MongoDB Atlas
enter image description here

答案 1 :(得分:1)

确保已将公用IP列入白名单。您可以通过谷歌搜索“我的IP是什么”来找到它。