如果猫鼬无法连接到我的数据库,我该如何设置错误处理回调?
我知道
connection.on('open', function () { ... });
但是有没有类似的东西
connection.on('error', function (err) { ... });
?
如果猫鼬无法连接到我的数据库,我该如何设置错误处理回调?
我知道
connection.on('open', function () { ... });
但是有没有类似的东西
connection.on('error', function (err) { ... });
?
当您连接时,您可以在回调中获取错误:
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/
万一有人遇到这种情况,我正在运行的 Mongoose 版本(3.4)按照问题中的说明工作。所以下面可能会返回错误。
connection.on('error', function (err) { ... });
正如我们在错误处理的 mongoose 文档中看到的那样,由于connect()方法返回一个 Promise,因此该 Promisecatch
是与 mongoose 连接一起使用的选项。
因此,要处理初始连接错误,您应该使用.catch()
or try/catch
with 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
是一种更清洁的方式。
迟到的答案,但如果你想保持服务器运行,你可以使用这个:
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");
});