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.
Each Mongoose connection has a close() method that takes an optional callback function. If you are using the default connection you call it like the following code snippet does: mongoose. connection.
There is no need for closing the connection explicitly. This way the application avoids creating and closing connections (which is an expensive operation).
The best way to stop mongoose activity in your yard is to make the environment unappealing to their survival. Remove or protect potential food sources. Cover vegetable gardens with mesh or other materials that mongooses cannot penetrate.
save(doc); // Update the document } else { db. close(); // Closing the connection } }); }); }); With asynchronous nature, if the process of updating the document takes longer, then when cursor reaches the end of documents, database connection is closed. Not all updates are saved to the database.
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.
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With