Javier Fuentes
Javier Fuentes

Reputation: 43

how to properly connect to mongodb.atlas? MongoNetworkError

I am learning how to use MongoDB with node.js, so I am making a restful API as practice.

But I keep getting "MongoNetworkError: getaddrinfo ENOTFOUND" whenever I try to connect to atlas for mongo.

My code at server.js:

// call the packages
var bodyParser = require('body-parser');
var Bear = require('./app/models/bear');
var mongoose = require('mongoose');

var express = require('express');
var app = express();

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://<userName>:<pasword>@cluster0-<someCharacters>.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect( err => {
  console.log(err);
  //const collection = client.db("test").collection("devices");
  client.close();
});

/*rest of the code is commented out*/
...

It logs the following error:

{ MongoNetworkError: failed to connect to server [cluster0-<someCharacters>.mongodb.net:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND cluster0-<someCharacters>.mongodb.net cluster0-<someCharacters>.mongodb.net:27017]
at Pool.<anonymous> (/app/node_modules/mongodb-core/lib/topologies/server.js:431:11)
at Pool.emit (events.js:198:13)
at connect (/app/node_modules/mongodb-core/lib/connection/pool.js:557:14)
at makeConnection (/app/node_modules/mongodb-core/lib/connection/connect.js:39:11)
at callback (/app/node_modules/mongodb-core/lib/connection/connect.js:261:5)
at Socket.err (/app/node_modules/mongodb-core/lib/connection/connect.js:286:7)
at Object.onceWrapper (events.js:286:20)
at Socket.emit (events.js:198:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }

notes:

what might I be doing wrong?

Upvotes: 1

Views: 369

Answers (1)

Yilmaz
Yilmaz

Reputation: 49729

u installed mongoose but you are trying to connect with mongodb package. since you installed mongoose

const mongoUri="your connection string here"
mongoose.connect(mongoUri,{useNewUrlParser:true})
.catch((e)=>{
    console.log(e.message)
    process.exit(1)
})
.then(()=>{
    console.log("connected to Mongo Atlas")
})

mongoose.connect return promise. if there is an error, connection will be rejected, it will log the error and then exit the process. if connection is success, that means promise is resolved, so it will connect and then will log the "connected to Mongo Atlas"

However i suggest you to check your connection string. it should have "+srv", something like this

  mongodb+srv://

Upvotes: 1

Related Questions