【问题标题】:uable to connect to mongdb Atlas from nodejs using mongoose无法使用 mongoose 从 nodejs 连接到 mongodb Atlas
【发布时间】:2020-03-24 18:04:29
【问题描述】:

这是我得到的错误。请帮忙解决这个问题

代码

 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();
 });

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在调用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();
    });
    

    我希望这会有所帮助。

    【讨论】:

    • 运气不好..还是一样的错误........“连接到数据库时出错”,我不明白一点 1.我禁用防火墙 2.我将我的白名单IP 和 0.0.0.0 也允许...仍然显示错误
    • 只是为了确认,db URI 的 userName:password 部分是占位符,对吗?您是否也可以尝试将 URI 更改为指向 MongoDB 的本地实例,看看是否可行?
    猜你喜欢
    • 2020-02-22
    • 2020-07-25
    • 2020-06-16
    • 2019-03-14
    • 2020-09-13
    • 2021-06-25
    • 2019-12-30
    • 2021-09-20
    • 2021-08-29
    相关资源
    最近更新 更多