无法从本地节点应用程序连接 MongoDB Atlas

Unable to Connect with MongoDB Atlas from Local Node App

我在 atlas 上创建了一个集群,并尝试使用我的节点应用程序进行连接,并使用 mongoose 记录连接状态。我已将我的 IP 列入白名单并正确设置所有内容,但我不断收到 UnhandledPromiseRejectionWarning.

这是我的 db.js 代码。在 mongooose.connect(url, opts).

上引发错误
 const mongoose = require('mongoose');

 const db_connect = async () => {
 const conn_string = await mongoose.connect('mongodb+srv://devjoe: 
    <password_hidden_delibarately>@devcamper-gs1nb.mongodb.net/devcamper?retry 
    Writes=true&w=majority', 
   {
        useCreateIndex: true,
        useNewUrlParser: true,
        useFindAndModify: false,
        useUnifiedTopology: true
   }); 

   console.log(`connection string: ${conn_string.connection.host}`);

}

module.exports = db_connect;

server.js 文件中,我只是在使用 commonjs 模块导入后调用了类似 db_connect(); 的函数。

任何帮助将不胜感激,因为我找不到问题所在。谢谢。

如果解决方案不起作用,您也可以尝试此方法:

const mongoose = require("mongoose");

const db_connect = () => {
  try {
    const conn_string = mongoose.connect(
      "mongodb+srv://devjoe: <*****************>@devcamper-gs1nb.mongodb.net/devcamper?retry Writes=true&w=majority",
      {
        useCreateIndex: true,
        useNewUrlParser: true,
        useFindAndModify: false,
        useUnifiedTopology: true
      }
    );

    console.log(`connection string: ${conn_string.connection.host}`);
  } catch {
    console.log(`not connected to : ${conn_string.connection.host}`);
  }
};

module.exports = db_connect;

我刚刚在我的电脑上测试了这个解决方案,它有效!

但是,如果 none 有效,可以向您发送我是如何进行连接的。