Do I need to manually close a mongoose connection?

New to Node, Mongoose & Mongodb – haven’t read the source code…

I have a Node application which opens a file, parses the lines into records and saves the records to mongodb. The records are Mongoose model objects, and to save them to mongodb all I do is invoke the save method on them.

So now I’m all worried about the connection that mongoose is managing db = mongoose.connect(url). Do I need to manually close it? If so, when should I close it (since everything is happening async it is hard to say when to close the connection)?

It seems that mongoose doesn’t only keep the connection open, but also it keeps my script from terminating. Can I safely close the mongoose connection after I’ve called save on all my objects? Otherwise given the async nature of the save, it would be difficult to know exactly when shutdown the connection.

You do need to call mongoose.disconnect() to close the connection, but you also need to wait until all save calls have completed their async work (i.e. called their callback) before doing that.

So either keep a simple count of how many are still outstanding to keep track or use a flow control framework like async to do something a bit more elegant.

You should close a mongoose connection when a Node POSIX signal is happening. SIGINT process is triggered when Ctrl-C has been pressed on terminal or a server shutdown.

Another possible scenario is to close a connection when a data streaming is done. Anyway is more recommended to connect on startup and disconnect on shutdown.

Read More:   Center (proportional font) text in an HTML5 canvas

This is the code for disconnection on a SIGINT signal.

// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
  mongoose.connection.close(function () {
    console.log('Mongoose disconnected on app termination');

What JohnnyHK said is correct. Add “SIGTERM” as well.

Simple example to use connection.close()

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts