ProgramingTip

몽구스 연결 오류가

bestdevel 2020. 11. 16. 21:59
반응형

몽구스 연결 오류가


mongoose가 내 DB에 수없는 경우 오류 처리에 대한 응급 처치 수 있습니까?

나는 알고있다

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('mongodb://localhost/dbname',function(err) {
    if (err)
        return console.error(err);
});

우리의 moongose ​​문서에서 볼 수있는 오류 처리 때문에, 연결 () 메소드가 반환 약속, 약속은 catch몽구스 연결에 사용하는 옵션이다.

따라서, 초기 연결 오류를 처리하기 위해, 당신은 .catch()수채화이나 try/catchasync/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);
}

IMHO, 사용하는 것이 catch더 육종 방법 이라고 생각합니다 .

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

반응형