0

I am currently testing out MongoDB(4.4) Drivers with nodeJS(no mongoose) and trying to connect to localhost:27107. The code below is pretty much copy/paste from the official documentation test code. MongoDB is nicely running in the back. However, on my command line I get error messages seen as below. Could anyone help me with solving this?

error message:

MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27107 at Timeout._onTimeout (/Users/miya/Desktop/FruitsProject/node_modules/mongodb/lib/core/sdam/topology.js:438:30) at listOnTimeout (internal/timers.js:557:17) at processTimers (internal/timers.js:500:7) { reason: TopologyDescription { type: 'Single', setName: null, maxSetVersion: null, maxElectionId: null, servers: Map(1) { 'localhost:27107' => [ServerDescription] }, stale: false, compatible: true, compatibilityError: null, logicalSessionTimeoutMinutes: null, heartbeatFrequencyMS: 10000, localThresholdMS: 15, commonWireVersion: null } }

My code in app.js looks like this;

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

// Connection URI
const uri =
  "mongodb://localhost:27107";

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

async function run() {
  try {
    // Connect the client to the server
    await client.connect();

    // Establish and verify connection
    await client.db("admin").command({ ping: 1 });
    console.log("Connected successfully to server");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

const dbName = "fruitDB";

Thanks in advance!

Miya
  • 5
  • 1

1 Answers1

0

this thing happens most of the time may be there is Ip restriction issues or anyother to resolve this issue there are two ways

  1. use mongoose instead of mongodb lib here is the code for connection

  var mongoose = require('mongoose');
  var mongoDB = 'mongodb://127.0.0.1/my_database';
  mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'MongoDB connection error:'));

2)if you are using atlas then use the connection string for 2 or lower nodejs version

Apoorva Chikara
  • 1
  • 3
  • 18
  • 29
Bilal Khursheed
  • 605
  • 4
  • 11