Home > Software engineering >  Can't access MongoDB on localhost in Node.js
Can't access MongoDB on localhost in Node.js

Time:11-12

I'm trying to run MongoDB in Node.js. I have installed the community server version of MongoDB (v. 5.0.3) under C:\mongodb.

In the subfolder "data" I have created another folder, "db", which is currently empty.

When I run mongoDB in mongo.exe, in the Windows terminal or even in the terminal in Node.js, everything seems to work. I can view my databases and create new databases and collections. I'm also able to access my databases in Compass (connection mongodb://localhost:27017).

As I said, my "data/db" folder is empty, even though I have created a new database, so it seems that my databases are stored somewhere else. Is this a problem?

In Node.js, I'm attempting to connect to MongoDB with Mongoose. I have tried a couple of different approaches with varying success. This code is always the same:

// Dependencies:
const express = require('express')
const app = express()
const mongoose = require('mongoose')

// Validate connection:
mongoose.connection.once('open', () => console.log('Connected do database'))
mongoose.connection.on('error', err => console.error('connection error:', err))

app.listen(5000, () => console.log('Server started'))

This URL works (seemingly):

// Connecting to database:
mongoose.connect('mongodb://127.0.0.1:27017/testdb', { useNewUrlParser: true })

In the console, I get "Server started" followed by "Connected to database".

However, this URL, which was suggested in a YouTube tutorial, does not work:

// Connecting to database:
mongoose.connect('mongodb://localhost/testdb', { useNewUrlParser: true })

In the console I get "Server started" but not "Connected to database". Then, after half a minute, the app crashes and I get the following error message (I have censored some personal information):

connection error: MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at NativeConnection.Connection.openUri (C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\connection.js:797:32)
    at C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\index.js:330:10
    at C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\index.js:1151:10)
    at Mongoose.connect (C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\index.js:329:20)
    at Object.<anonymous> (C:\Users\xxx\Documents\xxx\xxx\xxx\app.js:13:10)
    at Module._compile (node:internal/modules/cjs/loader:1095:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}
node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at NativeConnection.Connection.openUri (C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\connection.js:797:32)
    at C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\index.js:330:10
    at C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\index.js:1151:10)
    at Mongoose.connect (C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongoose\lib\index.js:329:20)
    at Object.<anonymous> (C:\Users\xxx\Documents\xxx\xxx\xxx\app.js:13:10)
    at Module._compile (node:internal/modules/cjs/loader:1095:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        _hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 4303888,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongodb\lib\cmap\connect.js:293:20)
            at Socket.<anonymous> (C:\Users\xxx\Documents\xxx\xxx\xxx\node_modules\mongodb\lib\cmap\connect.js:267:22)
            at Object.onceWrapper (node:events:510:26)
            at Socket.emit (node:events:390:28)
            at emitErrorNT (node:internal/streams/destroy:164:8)
            at emitErrorCloseNT (node:internal/streams/destroy:129:3)
            at processTicksAndRejections (node:internal/process/task_queues:83:21)
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}

Node.js v17.0.1
[nodemon] app crashed - waiting for file changes before starting...

Is my setup wrong, since I can't access MongoDB on localhost?

CodePudding user response:

Your setup is correct, but localhost seems to resolve to the IPv6 IP of your loop-back network device ::1, rather than the IPv4 address (127.0.0.1). MongoDB, by default, binds to the 127.0.0.1 address, I believe, and that's why you can't reach it using the ::1 address.

  1. There are several options here: keep using the 127.0.0.1 IP -- why not?
  2. Edit the mongodb config to bind to ::1 instead.
  3. Change what localhost resolves to. In linux you edit /etc/hosts for that, not sure about Windows.
  • Related