78

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

我知道

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

但是有没有类似的东西

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

?

4

6 回答 6

121

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

mongoose.connect('mongodb://localhost/dbname', function(err) {
    if (err) throw err;
});
于 2011-07-13T14:41:14.630 回答
42

您可以使用许多猫鼬回调,

// 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/

于 2015-12-05T16:01:39.447 回答
21

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

connection.on('error', function (err) { ... });
于 2013-09-01T21:43:22.607 回答
8

正如我们在错误处理的 mongoose 文档中看到的那样,由于connect()方法返回一个 Promise,因此该 Promisecatch是与 mongoose 连接一起使用的选项。

因此,要处理初始连接错误,您应该使用.catch()or try/catchwith async/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是一种更清洁的方式。

于 2019-08-25T22:09:49.943 回答
2

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

mongoose.connect('mongodb://localhost/dbname',function(err) {
    if (err)
        return console.error(err);
});
于 2015-06-21T19:00:19.957 回答
0
  • 处理(捕获)连接异常
  • 处理其他连接错误
  • 成功连接时显示一条消息
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");
});
于 2020-09-18T20:42:50.933 回答