简体   繁体   中英

can't connect to mongdb nodejs

i'm facing some issue when trying to connect to mongodb using my nodejs app. heres the code

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

and heres the Output:

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'
}

But when I tried to do a test connection with Mongodb Compass, I got the same problem.

then I tried Mongodb Compass using Windows VPS from the Google Cloud Platform, and it worked,

then, where did it go wrong?

the device that I use is Macbook Air early 2015 with MacOs mojave

I would recommend you not to use raw connection instead you can use mongoose as an ODM to work with it here is the ref link

If you create the db in mongodb cloud, you need to configure the ip address in Network Access in the mongodb cloud panel.

use 0.0.0.0/0 if you want to allow access from any ip, or enter your ip.

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