如果猫鼬无法连接到数据库,如何设置错误处理的回调?
我知道
connection.on('open', function () { ... });
但是有什么类似的东西
connection.on('error', function (err) { ... });
?
Answers:
连接后,您可以在回调中获取错误:
mongoose.connect('mongodb://localhost/dbname', function(err) {
    if (err) throw err;
});
    您可以使用许多猫鼬回调,
// 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/
正如我们在错误处理的猫鼬文档中所看到的那样,由于connect()方法返回Promise,所以promisecatch是用于猫鼬连接的选项。
因此,要处理初始连接错误,应将.catch()或try/catch与配合使用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是一种更清洁的方法。
UnhandledPromiseRejectionWarning: ReferenceError: handleError is not defined
                    catch()-感谢您的澄清
                    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");
});
    
connection.on('error', function (err) { ... });现在都可以在3.X中实现。