可以使用猫鼬从nodejs连接到mongdb Atlas

时间:2020-03-24 07:00:15

标签: node.js mongodb mongoose

enter image description here这是我遇到的错误。请帮助解决此问题

代码

 const MongoClient = require('mongodb').MongoClient;
 const uri = "mongodb+srv://userName:password@saichaitanyacluster-1m22k.mongodb.net/test?retryWrites=true&w=majority";
 const client = new MongoClient(uri, { useNewUrlParser: true });
 client.connect(err => {
   const collection = client.db("test").collection("devices");

   client.close();
 });

1 个答案:

答案 0 :(得分:0)

在致电client.db()之前,应添加检查以确认连接中没有错误。连接代码应如下所示:

// ...Everything that was here before

client.connect(err => {
  if (err) {
    console.log("There was an error connecting to the database");

    // Any other logic that you want to use to handle the error should live here.

    // Add a return statement to help avoid executing 
    // the code below that relies on a successful connection
    return; 
  }
  const collection = client.db("test").collection("devices");

  client.close();
});

我希望这会有所帮助。