So my attempt to use mongodb for the first time (test.js, copy and past from the tutorial):
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/local", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
When I launch node test.js, terminal doesn't show any error, but I doesn't end. It's stuck after logging "We are connected", waiting for something that I don't know. Is this normal? Thanks.
On the other hand, I have no problems using the mongo executable:
mongo
show dbs
And rest interface works, http://localhost:28017/listDatabases?text=1 shows:
{ "databases" : [
{ "name" : "local",
"sizeOnDisk" : 1,
"empty" : true } ],
"totalSize" : 0 }
MongoClient opens a tcp connection to mongodb. Whenever you do this, it prevents the node event loop from terminating your app because it is waiting for data over the tcp socket.
In the case of your example, you have connected so now you can start making queries to the database inside the callback.
As Roman indicated, you need to close your connection to MongoDB when you're done with it or it will hold the program open.
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/local", function(err, db) {
if(!err) {
console.log("We are connected");
}
// Use db
...
// Done with db so close it.
db.close();
});