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?