简体   繁体   中英

How to connect to mongoDB Atlas using mongoose

我正在尝试通过 Mongoose.connect() 连接到 mongoDB Atlas 上的集群,但是每次我尝试连接时都会收到异常“MongoError:身份验证失败”我知道 MongoDB Atlas 是新的 mongo 即服务,它可能不是猫鼬支持了吗?。

The answer in this related post is correct. You should:

  • not mix options with connection string (if done so)
  • make sure your IP you are running on is whitelisted and your network allows connections to Atlas
  • make sure the user has sufficient permissions
  • use the connection string as is provided by atlas and just provide it to

    mongoose.connect(uri);

MongoError: authentication fails - It means your name or password or dbname is not correct -

uri sample -

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

Suppose username is - najim & password is 1234 & dbname is pets (Note - default dbname is test but you can write whatever you want) then my uri will be with above credentails -

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

to connect with 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");
  }
try {
mongoose.connect( uri, {useNewUrlParser: true, useUnifiedTopology: true}, () =>
console.log("connected"));    
}catch (error) { 
console.log("could not connect");    
}

this works fine , try it

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/”也在atlas中,在安全进入网络访问,会有小按钮edit和delete点击edit,在edit中,会出现两个选项,第一个选项是 ADD CURRENT IP ADRESS & 第二个选项将是 ALLOW ACCESS FROM ANYWHERE 转到第一个选项,然后单击确认

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