Search code examples
javascriptnode.jsmongodb

Can't connect to MongoClient using Node


i made a simple program to connect to my mongoDB database

const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const bodyParser = require('body-parser');

let db = null;
const url = 'mongodb://localhost:27017';
const dbName = 'chatbotdb';

const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({extended: false});

app.use(jsonParser);
app.use(urlencodedParser);

MongoClient.connect(url, function(err, client) {
    assert.equal(null, err);
    console.log("This log is never shown.");

    db = client.db(dbName);
    
});

app.listen(3000);
console.log('Server running on: localhost:3000'); //this log is always shown

i was expecting to see the log of connection to mongoDB, i already have MongoDBCompass installed and my server is running


Solution

  • The node.js driver connects lazily, so you won't actually see any connection to the server until you do some operation that requires connecting to the server.

    db = client.db(dbName) can be performed with the data available on the client side without connecting.

    Try ping since that requires a response from the server.