是否存在mongoose connect错误回调

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)

  • 这似乎不起作用.我可以用一个糟糕的uri来提供它,并且错误总是返回undefined. (9认同)
  • @evilcelery mongoose中的所有查询都是缓冲的,所以一旦你重新连接到db就应该执行它们,这很好,不应该是未知状态的原因. (2认同)
  • 这在较新的Mongoose版本(3.X)中不起作用。请参阅Asta的答案以获取有效的解决方案。 (2认同)

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/

  • on error 回调不再提供错误。它只是一个布尔值,表示 true。 (2认同)

Ast*_*sta 21

如果有人发生这种情况,我正在运行的Mongoose版本(3.4)按照问题中的说明工作.因此以下内容可能会返回错误.

connection.on('error', function (err) { ... });
Run Code Online (Sandbox Code Playgroud)


cod*_*ade 6

正如我们在错误处理的 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是一种更清洁的方式。