简体   繁体   中英

Having trouble connecting nodejs to mongoDB Atlas

I am having trouble connecting nodejs and atlas.

This is my code

var mongoose = require('mongoose')
var mongoDB =
    'mongodb+srv://Yeon:yeoyeon1@cluster0.nnzsw.mongodb.net/local_library?retryWrites=true&w=majority'
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true })
var db = mongoose.connection
db.on('error', console.error.bind(console, 'MongoDB connection error: '))

And This is error code

MongoDB connection error:  Error: querySrv ETIMEOUT _mongodb._tcp.cluster0.nnzsw.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) {
  errno: undefined,
  code: 'ETIMEOUT',
  syscall: 'querySrv',
  hostname: '_mongodb._tcp.cluster0.nnzsw.mongodb.net'
}

i've switched from mongodb+src to mongodb like this The error code only got longer, but it was not resolved

var mongoDB =
    'mongodb://Yeon:dusrjf4346@cluster0.nnzsw.mongodb.net/local_library?retryWrites=true&w=majority'

And I've done all three of these.

First Make sure your IP is whitelisted like the above suggestions. The easiest solution is the "All IPs" whitelist of 0.0.0.0/0

Second Check your VPN if you are using one. I was trying to connect to the cluster while connected to a VPN. Once I turned off my VPN, I was able to connect.

Third Make sure your internet settings are not preventing you from connecting to the cluster. My home Xfinity wifi security settings were set too high and this was preventing the connection. I think the router was not allowing a connection to port 27017. One way to test if this issue is occurring is to tether your computer to your phone for internet instead of your wifi and try connecting. I was able to connect using my iPhone as a hotspot for internet. I reset my router to factory settings which fixed the issue.

However, Nothing solved my problem.
I think my password and dbname is right

Use this

const mongoose = require("mongoose");

mongoose.connect("MONGO_URI", {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
});

const connection = mongoose.connection;
connection.once('open', () => {
  console.log('MongoDB database connection established successfully');
});

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