8

node-mongodb-native node.js client hangs when MongoClient.connect(...), but mongodb-client (shell command line) works on terminal. Any clues?

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(
    'mongodb://my.mongo.db.server.ip:27017/test',
     function(err, db) {

        if(err) throw err;
        console.log("shows during connect call back");

        });

// When load into node shell, it hangs forever
Andrew_1510
  • 12,258
  • 9
  • 51
  • 52
  • 1
    use the mongoose nodejs client. Works like charm. – V31 Feb 18 '14 at 08:59
  • Thank you, but supposedly mongoose get `ODM`. Isn't it a little overkill? – Andrew_1510 Feb 18 '14 at 10:21
  • I would not consider it as an overkill because of the benefits it provides like structered data, having definite models to your data etc. With all these features it maintains the flexibility that MongoDb has to offer us. – V31 Feb 18 '14 at 10:29
  • 3
    Well I would suggest ```mongojs``` library which is more like thin wrapper on native driver. This does not force you do use the predefined structures which what NoSQL tries to avoid. – Risto Novik Feb 18 '14 at 11:32
  • just tried `mongojs` and `mongoose`, `mongojs` works as `mongodb` itself, nice interface. – Andrew_1510 Feb 18 '14 at 14:18
  • But back to your question what you mean by hanging ? If you execute the script and it does not end ? If yes, then it's probably the reason of mongodb connection which is left open you need to close it. – Risto Novik Feb 19 '14 at 08:43
  • jurka, by hanging, it means nothing return, it stay there with nothing occurs. – Andrew_1510 Feb 19 '14 at 10:18
  • I'm having the same problem. Not sure why node-mongodb-native takes so long to connect while the mongo shell connects in a flash. Would love if someone could actually answer the original question. – Sam Hiatt Apr 16 '15 at 00:23
  • @V31 is there any reason mongoose would connect when the mongodb package hangs? Does it use its own driver instead of using the mongodb client internally? – Andy Jun 13 '16 at 19:09

2 Answers2

5

It's been a long time since this question has been asked, but I'll post an answer for those wishing to use mongodb as opposed to mongoose or mongojs (at the time of this writing mongojs depends on an older insecure version of the mongodb driver).

TL;DR Version

The program executes normally, but adding the line db.close(); will allow your program to terminate normally:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(
    'mongodb://my.mongo.db.server.ip:27017/test',
     function(err, db) {
        if(err) throw err;
        console.log("shows during connect call back");
        db.close(); //call this when you are done.
        });

Why Node Appears to Hang When Using mongodb.connect()

As explained in this answer, node will not exit when it has a callback waiting for an event.

In this case, connect() registers a callback that waits for the event 'close' to be emitted, indicating that all database connections have been closed. This is why unless you call db.close(), your script will appear to hang. Note however, everything you code will execute, your program will just not terminate normally.

An Example

To demonstrate, if you put the following code block into a file called connect.js...

const MongoClient = require('mongodb').MongoClient;
async function dbconnect() {
console.log("This will print.");

const db = await MongoClient.connect(
    'mongodb://my.mongo.db.server.ip:27017/test');

console.log("This will print too!");

And execute it within a terminal...

$ node connect.js

the result will be:

$ node connect.js
This will print.
This will print too!

You will get no further command line prompts.

In conclusion remember to close your database connections, and all will be well in the world!

  • 1
    Awesome! Great thanks for clear and detail sharing – Nam G VU Dec 11 '22 at 05:16
  • The return type of `MongoClient.connect` is `MongoClient`, as such, it should be called client or mongoClient, not `db`. Calling it `db` is confusing because there is still a call to `.db('foo')` needed to get the actual database. – sezanzeb Jun 06 '23 at 08:54
0

For anyone else facing a similar issue, all I had to do was add a .catch and it worked fine from there on:

const mongodb = require("mongodb");

const connectDb = mongodb.MongoClient.connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).catch(err =>
    res.status(400).json({ msg: `Could not connect to MongoDB`, err })
);

module.exports = connectDb;

Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49