如何使用 mongoose 连接到 mongoDB Atlas

How to connect to mongoDB Atlas using mongoose

我正在尝试通过 Mongoose.connect() 连接到 mongoDB Atlas 上的集群,但每次我尝试连接时都会出现异常 "MongoError: authentication fail" 我知道 MongoDB Atlas 是新的 mongo 服务,mongoose 还不支持它吗?

是正确的。你应该:

  • 不要将选项与连接字符串混合(如果这样做)
  • 确保您 运行 所在的 IP 已列入白名单,并且您的网络允许连接到 Atlas
  • 确保用户有足够的权限
  • 按原样使用atlas提供的连接字符串,只提供给

    mongoose.connect(uri);
    
try {
mongoose.connect( uri, {useNewUrlParser: true, useUnifiedTopology: true}, () =>
console.log("connected"));    
}catch (error) { 
console.log("could not connect");    
}

这个很好用,试一试

MongoError: authentication fails - 这意味着您的名称或密码或 dbname 不正确 -

uri 样本 -

const uri =
    "mongodb+srv://<username>:<password>@firstcluster.4rc4s.mongodb.net/<dbname>?retryWrites=true&w=majority";

假设用户名是 - najim & 密码是 1234 & 数据库名是 pets (注意- 默认的 dbname 是 test 但你可以写任何你想要的)然后我的 uri 将带有上面的 credentails -

const  mongoAtlasUri =
        "mongodb+srv://najim:1234@firstcluster.4rc4s.mongodb.net/pets?retryWrites=true&w=majority";

与 moongoose 联系

try {
    // Connect to the MongoDB cluster
     mongoose.connect(
      mongoAtlasUri,
      { useNewUrlParser: true, useUnifiedTopology: true },
      () => console.log(" Mongoose is connected")
    );

  } catch (e) {
    console.log("could not connect");
  }
const mongoAtlasUri =
  "mongodb+srv://<username>:<password>@firstcluster.4rc4s.mongodb.net/<dbname>?retryWrites=true&w=majority";

try {
  // Connect to the MongoDB cluster
  mongoose.connect(
    mongoAtlasUri,
    { useNewUrlParser: true, useUnifiedTopology: true },
    () => console.log(" Mongoose is connected"),
  );
} catch (e) {
  console.log("could not connect");
}

const dbConnection = mongoose.connection;
dbConnection.on("error", (err) => console.log(`Connection error ${err}`));
dbConnection.once("open", () => console.log("Connected to DB!"));

"mongodb+srv://:@cluster0.vvkuk.mongodb.net/" 同样在图集中,在安全中转到网络访问,将有小按钮编辑和删除点击编辑,在编辑中,将有两个选项第一个选项是添加当前 IP 地址,第二个选项将是允许访问从任何地方 选择第一个选项,然后点击确认