pky*_*eck 65 javascript mongoose mongodb node.js
如果mongoose无法连接到我的数据库,如何设置错误处理的回调?
我知道
connection.on('open', function () { ... });
Run Code Online (Sandbox Code Playgroud)
但是有类似的东西
connection.on('error', function (err) { ... });
Run Code Online (Sandbox Code Playgroud)
?
evi*_*ery 113
连接时,您可以在回调中选择错误:
mongoose.connect('mongodb://localhost/dbname', function(err) {
if (err) throw err;
});
Run Code Online (Sandbox Code Playgroud)
thi*_*ttr 38
你可以使用很多猫鼬回叫,
// 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);
});
}); Run Code Online (Sandbox Code Playgroud)
更多信息:http://theholmesoffice.com/mongoose-connection-best-practice/
Ast*_*sta 21
如果有人发生这种情况,我正在运行的Mongoose版本(3.4)按照问题中的说明工作.因此以下内容可能会返回错误.
connection.on('error', function (err) { ... });
Run Code Online (Sandbox Code Playgroud)
正如我们在错误处理的 mongoose 文档中看到的,由于connect()方法返回一个 Promise,promisecatch是与 mongoose 连接一起使用的选项。
因此,要处理的初始连接错误,你应该使用.catch()或try/catch使用async/await。
这样,我们有两个选择:
使用.catch()方法:
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true })
.catch(error => console.error(error));
Run Code Online (Sandbox Code Playgroud)
或使用 try/catch:
try {
await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
console.error(error);
}
Run Code Online (Sandbox Code Playgroud)
恕我直言,我认为使用catch是一种更清洁的方式。