Beginner can't connect to db when trying to use mongodb with node on windows 10 in Visual Studio Code

I’m just learning mongodb for a JS class that uses Node JS, and I can’t get the first class example to work. I don’t know if it didn’t install correctly or if I missed a step. I use the terminal in Visual Studio Code to run the program. Here’s what I did:
I downloaded the MSI package for the community server and installed it with the default settings. It also installed Compass.
I did read on one website that I needed to add the C:\Program Files\MongoDB\Server\6.0\bin to Window’s Environmental Variables (Mongodb Installation on Windows, MacOS and linux)
I added C:\data\db

Using Command Prompt, I entered npm install mongodb

in Command Prompt, I entered mongod

Then in Visual Studio Code, where I have my program open, in the terminal command prompt, I change to the directory where my program is saved and run the following program by typing: node assignment4.js

PROGRAM:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:3000/";

MongoClient.connect(url, function (err, db) {
    if (err) {
        throw err;
    }
    var dbo = db.db("testDB");
    dbo.createCollection("customers", function(err, res) {
        if (err) {
            throw err;
        }
        console.log("customers Collection created");
        db.close();
    });
});

In the terminal, it pauses, and then spits this out:

C:\AIT618\node_modules\mongodb\lib\utils.js:365
                    throw error;
                    ^

MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:3000
    at Timeout._onTimeout (C:\AIT618\node_modules\mongodb\lib\sdam\topology.js:291:38)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:3000' => ServerDescription {
        address: 'localhost:3000',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 1639641464,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:3000
            at connectionFailureError (C:\AIT618\node_modules\mongodb\lib\cmap\connect.js:387:20)
            at Socket.<anonymous> (C:\AIT618\node_modules\mongodb\lib\cmap\connect.js:310:22)
            at Object.onceWrapper (node:events:642:26)
            at Socket.emit (node:events:527:28)
            at emitErrorNT (node:internal/streams/destroy:157:8)
            at emitErrorCloseNT (node:internal/streams/destroy:122:3)
            at processTicksAndRejections (node:internal/process/task_queues:83:21) {
          cause: Error: connect ECONNREFUSED 127.0.0.1:3000
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '127.0.0.1',
            port: 3000
          },
          [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) {}
}

I tried moving the saved program to different folder on the C drive and rerunning the npm install mongodb and the mongod while in that directory, but same error.

I read somewhere it may have to do with my firewall, so I reset the Windows Defender firewall settings, but no luck. I also have Kaspersky Anti-virus on my machine. But I’m guessing it’s something really easy that I’m too new to this to see or understand.

I’m so frustrated, and would really appreciate any help!

Thank you.

Hi @bockyweez, and welcome to the MongoDB Community forums! :wave:

The error states that your app cannot connect to MongoDB at localhost on port 3000.

A couple of questions:

  • Is the mongod process running?
  • The default port for MongoDB is 27017. Did you change that in the config/command line to be 3000?

The port 3000 comes from the JS program example from class – I don’t know how to change the config… it comes from this javascript:

var url = “mongodb://localhost:3000/”;
MongoClient.connect(url, function (err, db) … etc.

So when I enter in command prompt mongod this is what it spits out – I’m assuming it means it’s running? (does it matter what directory I’m in when I start it?)


`{"t":{"$date":"2022-10-06T20:14:09.278-04:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"-","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":17},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":17},"outgoing":{"minWireVersion":6,"maxWireVersion":17},"isInternalClient":true}}}
{"t":{"$date":"2022-10-06T20:14:12.137-04:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"thread1","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2022-10-06T20:14:12.142-04:00"},"s":"I",  "c":"NETWORK",  "id":4648602, "ctx":"thread1","msg":"Implicit TCP FastOpen in use."}
{"t":{"$date":"2022-10-06T20:14:12.144-04:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"thread1","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","namespace":"config.tenantMigrationDonors"}}
{"t":{"$date":"2022-10-06T20:14:12.144-04:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"thread1","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","namespace":"config.tenantMigrationRecipients"}}
{"t":{"$date":"2022-10-06T20:14:12.144-04:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"thread1","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"ShardSplitDonorService","namespace":"config.tenantSplitDonors"}}
{"t":{"$date":"2022-10-06T20:14:12.145-04:00"},"s":"I",  "c":"CONTROL",  "id":5945603, "ctx":"thread1","msg":"Multi threading initialized"}
{"t":{"$date":"2022-10-06T20:14:12.146-04:00"},"s":"I",  "c":"CONTROL",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":15440,"port":27017,"dbPath":"C:/data/db/","architecture":"64-bit","host":"RLB-Laptop"}}
{"t":{"$date":"2022-10-06T20:14:12.146-04:00"},"s":"I",  "c":"CONTROL",  "id":23398,   "ctx":"initandlisten","msg":"Target operating system minimum version","attr":{"targetMinOS":"Windows 7/Windows Server 2008 R2"}}
{"t":{"$date":"2022-10-06T20:14:12.146-04:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"6.0.2","gitVersion":"94fb7dfc8b974f1f5343e7ea394d0d9deedba50e","modules":[],"allocator":"tcmalloc","environment":{"distmod":"windows","distarch":"x86_64","target_arch":"x86_64"}}}}
{"t":{"$date":"2022-10-06T20:14:12.146-04:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Microsoft Windows 10","version":"10.0 (build 19044)"}}}
{"t":{"$date":"2022-10-06T20:14:12.146-04:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{}}}
{"t":{"$date":"2022-10-06T20:14:12.152-04:00"},"s":"I",  "c":"STORAGE",  "id":22270,   "ctx":"initandlisten","msg":"Storage engine to use detected by data files","attr":{"dbpath":"C:/data/db/","storageEngine":"wiredTiger"}}
{"t":{"$date":"2022-10-06T20:14:12.153-04:00"},"s":"I",  "c":"STORAGE",  "id":22315,   "ctx":"initandlisten","msg":"Opening WiredTiger","attr":{"config":"create,cache_size=7638M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,remove=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=2000),statistics_log=(wait=0),json_output=(error,message),verbose=[recovery_progress:1,checkpoint_progress:1,compact_progress:1,backup:0,checkpoint:0,compact:0,evict:0,history_store:0,recovery:0,rts:0,salvage:0,tiered:0,timestamp:0,transaction:0,verify:0,log:0],"}}
{"t":{"$date":"2022-10-06T20:14:13.384-04:00"},"s":"I",  "c":"STORAGE",  "id":4795906, "ctx":"initandlisten","msg":"WiredTiger opened","attr":{"durationMillis":1230}}
{"t":{"$date":"2022-10-06T20:14:13.384-04:00"},"s":"I",  "c":"RECOVERY", "id":23987,   "ctx":"initandlisten","msg":"WiredTiger recoveryTimestamp","attr":{"recoveryTimestamp":{"$timestamp":{"t":0,"i":0}}}}
{"t":{"$date":"2022-10-06T20:14:13.466-04:00"},"s":"W",  "c":"CONTROL",  "id":22120,   "ctx":"initandlisten","msg":"Access control is not enabled for the database. Read and write access to data and configuration is unrestricted","tags":["startupWarnings"]}
{"t":{"$date":"2022-10-06T20:14:13.466-04:00"},"s":"W",  "c":"CONTROL",  "id":22140,   "ctx":"initandlisten","msg":"This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning","tags":["startupWarnings"]}
{"t":{"$date":"2022-10-06T20:14:13.478-04:00"},"s":"I",  "c":"NETWORK",  "id":4915702, "ctx":"initandlisten","msg":"Updated wire specification","attr":{"oldSpec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":17},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":17},"outgoing":{"minWireVersion":6,"maxWireVersion":17},"isInternalClient":true},"newSpec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":17},"incomingInternalClient":{"minWireVersion":17,"maxWireVersion":17},"outgoing":{"minWireVersion":17,"maxWireVersion":17},"isInternalClient":true}}}
{"t":{"$date":"2022-10-06T20:14:13.478-04:00"},"s":"I",  "c":"REPL",     "id":5853300, "ctx":"initandlisten","msg":"current featureCompatibilityVersion value","attr":{"featureCompatibilityVersion":"6.0","context":"startup"}}
{"t":{"$date":"2022-10-06T20:14:13.479-04:00"},"s":"I",  "c":"STORAGE",  "id":5071100, "ctx":"initandlisten","msg":"Clearing temp directory"}
{"t":{"$date":"2022-10-06T20:14:13.483-04:00"},"s":"I",  "c":"CONTROL",  "id":20536,   "ctx":"initandlisten","msg":"Flow Control is enabled on this deployment"}
{"t":{"$date":"2022-10-06T20:14:13.845-04:00"},"s":"I",  "c":"FTDC",     "id":20625,   "ctx":"initandlisten","msg":"Initializing full-time diagnostic data capture","attr":{"dataDirectory":"C:/data/db/diagnostic.data"}}
{"t":{"$date":"2022-10-06T20:14:13.858-04:00"},"s":"I",  "c":"REPL",     "id":6015317, "ctx":"initandlisten","msg":"Setting new configuration state","attr":{"newState":"ConfigReplicationDisabled","oldState":"ConfigPreStart"}}
{"t":{"$date":"2022-10-06T20:14:13.858-04:00"},"s":"I",  "c":"STORAGE",  "id":22262,   "ctx":"initandlisten","msg":"Timestamp monitor starting"}
{"t":{"$date":"2022-10-06T20:14:13.865-04:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"127.0.0.1"}}
{"t":{"$date":"2022-10-06T20:14:13.865-04:00"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}`

This line (the last one in the log file you provided) is what we’re interested in. This means that the mongod process is indeed running and listening for connections. We can see that it is listening on port 27017. You would want to change your code to var url = "mongodb://localhost:27017";.

Port 3000 is most likely the port that your web application listens on.

Try making the change as I’ve mentioned above to see if you can get your application to connect to the MongoDB server.

1 Like

@Doug_Duncan thank you! – I changed that and I got some other errors but was able to figure it out from there.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.