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
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).
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.
});
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With