connection to the mongoDB server using node js

117 Views Asked by At

I am not able to establish the connection to the mongodb using node driver. Here's my code:

**const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");

// connection URL
const url = "mongodb://localhost:27017/";

// 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 to server successfully");

    const db = client.db(dbName);

    client.close();
});**

This is the response I'm getting back: Response image of terminal

I have already tried changing the address in the url from "localhost" to "127.0.0.1", but it didn't work. Please help me out!

mongod server response:

{"t":{"$date":"2023-08-21T22:40:34.908+05:30"},"s":"I",  "c":"REPL",     "id":5853300, "ctx":"initandlisten","msg":"current featureCompatibilityVersion value","attr":{"featureCompatibilityVersion":"7.0","context":"startup"}}
{"t":{"$date":"2023-08-21T22:40:34.909+05:30"},"s":"I",  "c":"STORAGE",  "id":5071100, "ctx":"initandlisten","msg":"Clearing temp directory"}
{"t":{"$date":"2023-08-21T22:40:34.911+05:30"},"s":"I",  "c":"CONTROL",  "id":6608200, "ctx":"initandlisten","msg":"Initializing cluster server parameters from disk"}
{"t":{"$date":"2023-08-21T22:40:34.911+05:30"},"s":"I",  "c":"CONTROL",  "id":20536,   "ctx":"initandlisten","msg":"Flow Control is enabled on this deployment"}
{"t":{"$date":"2023-08-21T22:40:35.117+05:30"},"s":"I",  "c":"FTDC",     "id":20625,   "ctx":"initandlisten","msg":"Initializing full-time diagnostic data capture","attr":{"dataDirectory":"C:/data/db/diagnostic.data"}}
{"t":{"$date":"2023-08-21T22:40:35.121+05:30"},"s":"I",  "c":"REPL",     "id":6015317, "ctx":"initandlisten","msg":"Setting new configuration state","attr":{"newState":"ConfigReplicationDisabled","oldState":"ConfigPreStart"}}
{"t":{"$date":"2023-08-21T22:40:35.121+05:30"},"s":"I",  "c":"STORAGE",  "id":22262,   "ctx":"initandlisten","msg":"Timestamp monitor starting"}
{"t":{"$date":"2023-08-21T22:40:35.125+05:30"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"127.0.0.1"}}
{"t":{"$date":"2023-08-21T22:40:35.125+05:30"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}

mongosh prompt in terminal

$ mongosh
Current Mongosh Log ID: 64e3a30074e0279acc8ee81f
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.5
Using MongoDB:          7.0.0
Using Mongosh:          1.10.5

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting
   2023-08-20T14:35:50.897+05:30: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------

test> 

response after running my app.js file

const timeoutError = new error_1.MongoServerSelectionError(Server selection timed out after ${serverSelectionTimeoutMS} ms, this.description); ^

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (C:\Users\abhis\OneDrive\Desktop\fruitsProject\node_modules\mongodb\lib\sdam\topology.js:278:38)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7) {
  reason: TopologyDescription {
    type: 'Single',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 261314343,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\abhis\OneDrive\Desktop\fruitsProject\node_modules\mongodb\lib\cmap\connect.js:367:20)
            at Socket.<anonymous> (C:\Users\abhis\OneDrive\Desktop\fruitsProject\node_modules\mongodb\lib\cmap\connect.js:290:22)
            at Object.onceWrapper (node:events:629:26)
            at Socket.emit (node:events:514:28)
            at emitErrorNT (node:internal/streams/destroy:151:8)
            at emitErrorCloseNT (node:internal/streams/destroy:116:3)
            at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
          cause: Error: connect ECONNREFUSED ::1:27017
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) {
            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '::1',
            port: 27017
          },
          [Symbol(errorLabels)]: Set(1) { 'ResetPool' }
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}

Node.js v18.17.0
1

There are 1 best solutions below

1
Ítalo Sérvio On

I believe that you need to add directConnection=true flag to force your operations to run on the host specified in your connection URI.

const client = new MongoClient("mongodb://127.0.0.1:27017/fruitsDB", {
  useNewUrlParser: true,
  directConnection: true,
});

Ref.: https://www.mongodb.com/docs/drivers/node/current/fundamentals/connection/connect/#direct-connection