繁体   English   中英

有没有 mongoose 连接错误回调

[英]is there a mongoose connect error callback

如果 mongoose 无法连接到我的数据库,我该如何设置错误处理回调?

我知道

connection.on('open', function () { ... });

但是有没有类似的东西

connection.on('error', function (err) { ... });

?

当您连接时,您可以在回调中获取错误:

mongoose.connect('mongodb://localhost/dbname', function(err) {
    if (err) throw err;
});

您可以使用许多 mongoose 回调,

 // CONNECTION EVENTS // When successfully connected mongoose.connection.on('connected', function () { console.log('Mongoose default connection open to ' + dbURI); }); // If the connection throws an error mongoose.connection.on('error',function (err) { console.log('Mongoose default connection error: ' + err); }); // When the connection is disconnected mongoose.connection.on('disconnected', function () { console.log('Mongoose default connection disconnected'); }); // If the Node process ends, close the Mongoose connection process.on('SIGINT', function() { mongoose.connection.close(function () { console.log('Mongoose default connection disconnected through app termination'); process.exit(0); }); });

更多信息: http://theholmesoffice.com/mongoose-connection-best-practice/

如果有人遇到这种情况,我正在运行的 Mongoose 版本(3.4)会按照问题中的说明工作。 所以下面可能会返回错误。

connection.on('error', function (err) { ... });

As we can see on the mongoose documentation for Error Handling , since the connect() method returns a Promise, the promise catch is the option to use with a mongoose connection.

因此,要处理初始连接错误,您应该使用.catch()try/catchasync/await

这样,我们有两种选择:

使用.catch()方法:

mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true })
.catch(error => console.error(error));

或使用 try/catch:

try {
    await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
    console.error(error);
}

恕我直言,我认为使用catch是一种更清洁的方式。

迟到的答案,但如果你想保持服务器运行,你可以使用这个:

mongoose.connect('mongodb://localhost/dbname',function(err) {
    if (err)
        return console.error(err);
});
  • 处理(捕获)连接异常
  • 处理其他连接错误
  • 成功连接时显示一条消息
mongoose.connect(
  "mongodb://..."
).catch((e) => {
  console.log("error connecting to mongoose!");
});
mongoose.connection.on("error", (e) => {
  console.log("mongo connect error!");
});
mongoose.connection.on("connected", () => {
  console.log("connected to mongo");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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