简体   繁体   中英

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 (ie 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.

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);
  });
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM