user1098965
user1098965

Reputation:

MongoDB with Node.js, script is waiting... for what?

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 }

Upvotes: 0

Views: 371

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 312115

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();
});

Upvotes: 0

Roman Shtylman
Roman Shtylman

Reputation: 661

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.

Upvotes: 1

Related Questions