programing

새 연결을 생성하지 않고 몽구스 연결 상태 확인

shortcode 2021. 1. 18. 08:22
반응형

새 연결을 생성하지 않고 몽구스 연결 상태 확인


Express 앱을로드하는 몇 가지 테스트, 즉 Supertest가 있습니다. 이 앱은 Mongoose 연결을 생성합니다. 테스트 내에서 해당 연결 상태를 확인하는 방법을 알고 싶습니다.

app.js에서

mongoose.connect(...)

test.js에서

console.log(mongoose.connection.readyState);

app.js 연결에 액세스하는 방법은 무엇입니까? test.js에서 동일한 매개 변수를 사용하여 연결하면 새 연결을 만들거나 기존 연결을 찾습니까?


mongoose 모듈은 싱글 톤 객체를 내보내기 때문에 연결 test.js상태를 확인 하기 위해 연결할 필요가 없습니다 .

// test.js
require('./app.js'); // which executes 'mongoose.connect()'

var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);

준비 상태 :

  • 0 : 연결 해제
  • 1 : 연결됨
  • 2 : 연결
  • 3 : 연결 해제

Express Server mongoDB 상태에 사용합니다. 여기서 express-healthcheck 미들웨어를 사용합니다.

// Define server status
const mongoose = require('mongoose');
const serverStatus = () => {
  return { 
     state: 'up', 
     dbState: mongoose.STATES[mongoose.connection.readyState] 
  }
};
//  Plug into middleware.
api.use('/api/uptime', require('express-healthcheck')({
  healthy: serverStatus
}));

DB 연결시 Postman 요청에이를 제공합니다.

{
  "state": "up",
  "dbState": "connected"
}

데이터베이스가 종료되었을 때이 응답을 제공합니다.

{
"state": "up",
"dbState": "disconnected"
}

(응답의 "업"은 내 Express Server 상태를 나타냄)

읽기 쉬움 (해석 할 숫자 없음)

참조 URL : https://stackoverflow.com/questions/19599543/check-mongoose-connection-state-without-creating-new-connection

반응형