首页 > 解决方案 > 无法连接到 mongdb nodejs

问题描述

尝试使用我的 nodejs 应用程序连接到 mongodb 时,我遇到了一些问题。这是代码

const { MongoClient } = require("mongodb");

async function main() {
  const uri =
    "mongodb+srv://xxxx:xxxx@xxxx.uj545.mongodb.net/xxxx?retryWrites=true&w=majority";
  const client = new MongoClient(uri);
  await client.connect();
  await listDatabases(client);
  try {
    await client.connect();
    await listDatabases(client);
  } catch (e) {
    console.error(e);
  } finally {
    await client.close();
  }
}

main().catch(console.error);

这是输出:

Error: queryTxt ETIMEOUT xxxx.uj545.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) {
  errno: undefined,
  code: 'ETIMEOUT',
  syscall: 'queryTxt',
  hostname: 'xxxx.uj545.mongodb.net'
}

但是当我尝试使用 Mongodb Compass 进行测试连接时,我遇到了同样的问题。

然后我使用 Google Cloud Platform 中的 Windows VPS 尝试了 Mongodb Compass,它成功了,

那么,到底哪里出错了?

我使用的设备是 2015 年初的 Macbook Air 和 MacOs mojave

标签: javascriptnode.jsmongodb

解决方案


我建议您不要使用原始连接,而是可以使用 mongoose 作为 ODM 来使用它,这是参考链接


推荐阅读