Connection open and close

2,248 views
Skip to first unread message

Sergey

unread,
Jun 26, 2011, 4:12:35 AM6/26/11
to Mongoose Node.JS ORM
Hello,
I am trying to use mongoose in the simple node.js RESTful web
service. I added the route that returns the list of the products that
are obtained from the database and sent to the client in the form of
JSON:
Here is mongoose related code:
exports.getAllProducts=function(callback){
mongoose.connect(connection_string);
var Product = getProductModel();
if(Product){
Product.find(function(err, pr){
if(err) throw err;
mongoose.disconnect();
if(pr){
var data = JSON.stringify(pr);
callback(data);
}
else
callback('some error occured');
});
}
else{
callback('sory, the product schema was not found');
}
};

I've faced the problem described in https://github.com/visionmedia/express/issues/561
The problem disappeared after I removed mongoose.disconnect(); line
from getAllProducts function.
In https://github.com/visionmedia/express/issues/561 I've noticed the
interesting dialog:
===
1. Ok, well the only reason I do close the connection is just because
that's how it is always done in every other DB driver/ORM I've used.
You open a connection, do stuff, and close the connection. Mongoose
handles all of that in the background? If so, that's pretty nice. I
just want to make sure it doesn't induce memory leaks or extraneous DB
connections or anything of that sort.
===
2. there's nothing wrong at all with keeping a connection open
===

My question is - really guys, what is the best practice in this
situation? Isn't is necessary to open/close the connection in each and
every call to DB? Or I can just open it once and re-use for each call
and it will not cause any issues?

Aaron Heckmann

unread,
Jul 19, 2011, 1:26:44 PM7/19/11
to mongoo...@googlegroups.com
Open it and leave it open until you close/shutdown your app.
--
Aaron


Jesse Sanford

unread,
Jul 19, 2011, 3:47:59 PM7/19/11
to mongoo...@googlegroups.com
Considering that all operations in node are single threaded all calls
via mongoose will run through that very same connection (socket)
correct?

Aaron Heckmann

unread,
Jul 21, 2011, 9:48:35 AM7/21/11
to mongoo...@googlegroups.com
Jesse, yes. I should note that the node-mongodb-native driver supports connection pooling as an option as well (not yet exposed, gh-410).

--
Aaron


Sergey

unread,
Jul 27, 2011, 10:29:03 PM7/27/11
to mongoo...@googlegroups.com
Thanks for the answers. I have faced the problem I don't know how to solve and which seems to be related to the connection cache.
Let's look at the code:

Here is the code of "db.module.js":

var mongoose = require('mongoose');
var databaseName = global.databaseName;
if(!databaseName)
  throw new Error('the database to work on is not defined');
var connection_string = 'mongodb://localhost/'+databaseName;
mongoose.connect(connection_string);
var Schema = mongoose.Schema;
var PersonSchema = new Schema({
  name: String
});
function getDbModel(callback){
  try{
    mongoose.model('Person', PersonSchema);
    callback(undefined,mongoose.model('Person', 'friends'));
  }catch(err){
    callback(err);
  }
}
exports.getDbModel=function(callback){
  getDbModel(function(err, model){
    if(err)
      callback(err);
    callback(undefined, model);
    });
};
and the code of "db.module.test.js":
function run(dbName, personName, next){
  global.databaseName=dbName;
  delete(require.cache[require.resolve('./db.module.js')]);
  var dbModule = require('./db.module.js');
  dbModule.getDbModel(function(err, model){
    if(err){
      console.log('obtaining model error: '+err);
      process.exit(1);
    }
    var person = new model();
    person.name = personName;
    person.save(function(err){
      if(err){
        console.log('saving  error: '+err);
        process.exit(1);
      }
      if(next)
        next();
      else
        process.exit(0);
    });
  });
}
run('db1','Jon', function(){run('db2','James');});

I expect the the outcome will be two databases "db1" and "db2", both of them contain collection "friends". db1's friends collection would have {name:"Jon"} item and db2's friends collection would have {name:"James"} item. But as the actual outcome is db1 database only! It has friends collection which contains two items:{name:"Jon"} and {name:"James"}!! It seems that the second run does not force the connection re-open and the connection from the 1st run is used!  As you can see I tried to work around the problem by clearing the module cache:   delete(require.cache[require.resolve('./db.module.js')]); but it does not help:(

Do you have any ideas on what's wrong with this code?

Sergey

unread,
Jul 28, 2011, 12:02:48 AM7/28/11
to mongoo...@googlegroups.com
Got it, I need to use createConnection instead of mongoose.connect if I need to connect to several different databases, here is the updated version of db.module.js:
var mongoose = require('mongoose');
var databaseName = global.databaseName;
if(!databaseName)
  throw new Error('the database to work on is not defined');
console.log('using '+databaseName);
var connection_string = 'mongodb://localhost/'+databaseName;
var connection = mongoose.createConnection(connection_string);
var Schema = mongoose.Schema;
var PersonSchema = new Schema({
  name: String
});

function getDbModel(callback){
  try{
    mongoose.model('Person', PersonSchema);
    callback(undefined,connection.model('Person', 'friends'));
Reply all
Reply to author
Forward
0 new messages