如何在mongoose中处理mongoDB关闭

时间:2023-02-06 02:32:51

All:

I am pretty new to mongoose, right now, I open MongoDB like:

我对mongoose很新,现在,我打开MongoDB就像:

db.js

var DB_URL = "mongodb://localhost/test/";

var mongoose = require("mongoose");

mongoose.connect(DB_URL);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
    console.log("OPEN DB...");
});

module.exports = mongoose;

I wonder: Is there anything I must do if I terminate Application using that mongoose connection by simply with CTRL+C? Will MongoDB know this connection has been closed( or how can I inform this)?

我想知道:如果我使用CTRL + C使用那个mongoose连接终止Application,我有什么必须做的吗? MongoDB是否知道此连接已关闭(或者我如何通知)?

This is especially helpful during DEV phase which the App may need to restart a lot.

这在应用程序可能需要重启很多的DEV阶段尤其有用。

Thanks

1 个解决方案

#1


2  

Well here is an idea that I think might be helpful. Node.js receives unix signals. So for example Ctrl+C sends a unix signal (SIGINT) to the Node.js application you're running in that terminal to terminate.

那么这是一个我认为可能有用的想法。 Node.js接收unix信号。因此,例如,Ctrl + C将一个unix信号(SIGINT)发送到您在该终端中运行的Node.js应用程序以终止。

Say you wanted to close your DB connection before shutting the node.js app. That way you can prevent lose of or damaging data. Well, a good way to do so is override the termination signal.

假设您想在关闭node.js应用程序之前关闭数据库连接。这样您就可以防止数据丢失或损坏。那么,一个好方法是覆盖终止信号。

To override the signal all you have to do is this:

要覆盖信号,您只需这样做:

process.on('SIGINT', function(params) {
    //Shut your db instance here. 
    //close or save other stuff. 
});

This way when you do CTRL+C it will shut things gracefully without risking damage.

这样当你执行CTRL + C时,它会优雅地关闭事物,而不会有损坏的风险。

#1


2  

Well here is an idea that I think might be helpful. Node.js receives unix signals. So for example Ctrl+C sends a unix signal (SIGINT) to the Node.js application you're running in that terminal to terminate.

那么这是一个我认为可能有用的想法。 Node.js接收unix信号。因此,例如,Ctrl + C将一个unix信号(SIGINT)发送到您在该终端中运行的Node.js应用程序以终止。

Say you wanted to close your DB connection before shutting the node.js app. That way you can prevent lose of or damaging data. Well, a good way to do so is override the termination signal.

假设您想在关闭node.js应用程序之前关闭数据库连接。这样您就可以防止数据丢失或损坏。那么,一个好方法是覆盖终止信号。

To override the signal all you have to do is this:

要覆盖信号,您只需这样做:

process.on('SIGINT', function(params) {
    //Shut your db instance here. 
    //close or save other stuff. 
});

This way when you do CTRL+C it will shut things gracefully without risking damage.

这样当你执行CTRL + C时,它会优雅地关闭事物,而不会有损坏的风险。