Do I need to manually close a mongoose connection?

2019-01-23 14:24发布

问题:

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.

回答1:

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.



回答2:

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.

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');
    process.exit(0);
  });
});


回答3:

What JohnnyHK said is correct. Add "SIGTERM" as well.

Simple example to use connection.close()

https://gist.github.com/pasupulaphani/9463004#file-mongoose_connet-js