Closing connection on server shutdown

186 views
Skip to first unread message

Mongo Rookie

unread,
Jun 30, 2013, 1:14:12 PM6/30/13
to mongoo...@googlegroups.com
Someone recently asked me if I was closing the mongoose connection on nodejs server shutdown (normal or error).  I open the connection like this:

  mongoose.connect('mongodb://localhost/mydb', function(err) {
    if (err) throw err;
  });

However I  never close/disconnect the connection.  I noticed that my connections seem to be getting disconnected so I imagine mongoose is being smart and closing the connection(s) for me.  My question is, should I be closing/disconnecting the connection when the server shuts down?  And how?




Alessio Dione

unread,
Jul 2, 2013, 6:29:33 AM7/2/13
to mongoo...@googlegroups.com
I explicitly close connection(s) to Mongo, a simple line of code like this:
    mongoose.connection.close(function() {
        logger.info('DAO - connection closed to ' +dbCfg.db_name + ' at address: ' + dbCfg.db_server_addr);

        typeof callback === 'function' && callback();
    });

Billy Newman

unread,
Jul 2, 2013, 8:38:16 AM7/2/13
to mongoo...@googlegroups.com
When do you do that?

Sent from my iPhone
--
Documentation - http://mongoosejs.com/
Plugins - http://plugins.mongoosejs.com/
Bug Reports - http://github.com/learnboost/mongoose
Production Examples - http://mongoosejs.tumblr.com/
StackOverflow - http://stackoverflow.com/questions/tagged/mongoose
Google Groups - https://groups.google.com/forum/?fromgroups#!forum/mongoose-orm
Twitter - https://twitter.com/mongoosejs
IRC - #mongoosejs
---
You received this message because you are subscribed to the Google Groups "Mongoose Node.JS ODM" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoose-orm...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Alessio Dione

unread,
Jul 2, 2013, 9:10:55 AM7/2/13
to mongoo...@googlegroups.com
Two cases:
 uncaughtException intercepted from NodeJS process (process.on("uncaughtException", function (err) {...}))
- manual shutdown of the application by means of SIGINT (process.on("SIGINT", function (err) {...}))

Billy Newman

unread,
Jul 2, 2013, 9:13:29 AM7/2/13
to mongoo...@googlegroups.com
Awesome thanks!

Also does mongoose have hooks to automatically do this as a safeguard?  It must as I have not been closing connections on shutdown (either case) and my connections are getting closed.


Alessio Dione

unread,
Jul 2, 2013, 11:58:58 AM7/2/13
to mongoo...@googlegroups.com
Actually, I think I need to correct my code: the proper way of closing connection should be:
mongoose.disconnect(function() {...})

This will loop on all open connections rather than acting only on the first one.
About the moongoose hooks: I'm not sure, haven't googled for that but I think it's simpler:
when the node process dies all open connections are closed as well. 

--
Alessio
Reply all
Reply to author
Forward
0 new messages