MVDash8
MVDash8

Reputation: 3

MongoDB hangs without NodeJS Response

I am trying to run a mongoDB server from NodeJS and I am having issues connecting to my server. I have started the server using mongod, but when I try to connect using the code below, the terminal just hangs and I do not get a "Connected successfully to server" response.


const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://127.0.0.1:27017'; //localhost

// Database Name
const dbName = 'fruitsDB';

// Create a new MongoClient
const client = new MongoClient(url, {useNewUrlParser: true });

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

I have confirmed that my db is running through mongosh. When I substitute the 127.0.0.1 for "localhost" in the url and try to connect, I get a "error: MongoNetworkError: connect ECONNREFUSED ::1:27017", which is why I switched to using 127.0.0.1 in the url.

Can anyone please help with this? Thanks in advance!

Upvotes: 0

Views: 59

Answers (1)

robertklep
robertklep

Reputation: 203484

According to the fine manual, MongoClient.connect() returns a Promise (it looks like callbacks have been deprecated).

Also, explicitly calling connect() has been made optional in v4.7.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://127.0.0.1:27017'; //localhost

// Database Name
const dbName = 'fruitsDB';

// Create a new MongoClient
const client = new MongoClient(url, {useNewUrlParser: true });

// Create an async IIFE wrapper so we can use `await`
void async function() {
  await client.connect();
  console.log("Connected successfully to server");

  const db = client.db(dbName);
  ...
  await client.close();
}();

(I left out error handling, but you'd use try/catch for that).

Upvotes: 0

Related Questions