2

Hi I am new to MongoDB and NodeJs. I am using "mongojs" module to simple read the data from mongodb. The code goes as follows:

var dbname = 'XXXX';
var databaseUrl = 'mongodb://localhost:27017/'+dbname;
var collections = ['candidate','cities','states','countries'];
var mongojs = require('mongojs');
var db = mongojs(databaseUrl, collections);

db.candidate.findOne({fname:'XXX'},function(err,doc){
    if(err){
        console.log(err);
    }
    else{
        console.log(doc);
    }
});
db.close();

When I run them in the terminal I get this error:

{ name: 'MongoError',
  message: 'server localhost:27017 sockets closed' }

Seems like the db.close() is getting executed before the data is fetched. How do we handle such kind of issues.

Norah
  • 65
  • 1
  • 5
  • 1
    "Asyncronus code". Read up. `.findOne()` has not "completed" when `db.close()` is being called. You also just about never close a database connection in real code. Read up on that as well. – Blakes Seven Jul 15 '15 at 10:34
  • possible duplicate of [When to close MongoDB database connection in Nodejs](http://stackoverflow.com/questions/8373905/when-to-close-mongodb-database-connection-in-nodejs) – Blakes Seven Jul 15 '15 at 10:36

1 Answers1

0

The above code is asynchronous. While the operation for db.candidate.findOne() is being carried out. The node does not wait for the process to complete and it starts executing another line. So simply putting, db.close() in the callback can solve this error.

var dbname = 'XXXX';
var databaseUrl = 'mongodb://localhost:27017/'+dbname;
var collections = ['candidate','cities','states','countries'];
var mongojs = require('mongojs');
var db = mongojs(databaseUrl, collections);

db.candidate.findOne({fname:'XXX'},function(err,doc){
    if(err){
        console.log(err);
    }
    else{
        console.log(doc);
    }
    db.close();
});

I am also a novice in node. So yes, @blake could be correct about what he said, we may never want to close the db connection.

Juvenik
  • 900
  • 1
  • 8
  • 26