source

mongoose 접속 오류 콜백이 발생합니까?

bestscript 2023. 3. 6. 21:13

mongoose 접속 오류 콜백이 발생합니까?

mongoose가 DB에 접속할 수 없는 경우 오류 처리를 위한 콜백을 설정하려면 어떻게 해야 합니까?

알고 있다

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

근데 이런 게 있어요?

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

?

연결 시 콜백에서 오류를 확인할 수 있습니다.

mongoose.connect('mongodb://localhost/dbname', function(err) {
    if (err) throw err;
});

사용할 수 있는 mongoose 콜백이 많이 있습니다.

// 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를 반환하므로 Promise는catch는 mongoose 연결에서 사용하는 옵션입니다.

따라서 초기 연결 오류를 처리하려면.catch()또는try/catch와 함께async/await.

이 방법에는 다음 두 가지 옵션이 있습니다.

사용방법.catch()방법:

mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true })
.catch(error => console.error(error));

또는 시도/실행 사용:

try {
    await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
    console.error(error);
}

IMHO는 제가 봤을 때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");
});

언급URL : https://stackoverflow.com/questions/6676499/is-there-a-mongoose-connect-error-callback