- 연결을 하다보니, db연결과 서버스타팅이 비동기적으로 일어나거나 이해하지 못하는 순서가 있었다.
- 이를 구조개선을 통해 재정렬하여 connection 파이프라인이 명확해지도록 해야겠다.
db.js
const mongoose = require("mongoose");
mongoose.set('strictQuery', false);
const mongooseConnect = async ()=>{
try{
await mongoose.connect(process.env.DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
// useFindAndModify: false,
// useCreateIndex: true,
}, ()=>{
console.log('연결되었습니다 db.js');
})
}
catch(err){
console.log(err)
}
}
module.exports = mongooseConnect;
- async-tryCatch 문을 통해 err를 뿜어내도록 정렬했고, mongooseConnect라는 함수로 감싸서 exports해줬다.
- 전에는 mongoose라는 이름으로 exports했는데, server.js에서 mongoose자체 리스너를 달아주고자 이름을 바꿨다.
server.js
const app = require('./app');
const http = require('http');
const mongooseConnect = require('./db');
const mongoose = require('mongoose');
const { logEvents, logger } = require('./middleware/logger')
const server = http.createServer(app);
mongooseConnect(); //db 연결 호출
mongoose.connection.once('open', ()=>{ //mongoose eventListener
server.listen(process.env.PORT, ()=>{
console.log('server.js에서'+process.env.PORT)
})
})
mongoose.connection.on('error', err => { //mongoose Error log
console.log(err);
logEvents(`${err.no}: ${err.code}\t${err.syscall}\t${err.hostname}`, 'mongoErrLog.log');
})
- mongoose library를 가져와서 .connection 메소드의 이벤트리스너를 달아줬다.
- db를 open 하고나서 서버를 켜주는 순서를 가지게되었당
- 에러가 나면 미리 지정해놨던 미들웨어 logEvents를 통해 에러 로그를 저장해준다.
- 인터넷 연결을 끄고 실행해보면
- 오늘 네이버 Deview 갔다와서 힘드니까 여기까지만..
'더이상 하지 않는 망한 프로젝트 > 프로젝트 개발 과정' 카테고리의 다른 글
[앱삼] 5. (frontend) React Router 세팅, 페이지 만들어놓기 (0) | 2023.03.03 |
---|---|
[앱삼] 4. (frontend) Redux-toolkit 구조 세팅 (0) | 2023.03.02 |
[앱삼] 2. MERN 풀스택 환경 기본세팅 - 4 (0) | 2023.02.26 |
[앱삼] 2. MERN 풀스택 환경 기본세팅 - 3 (0) | 2023.02.26 |
[앱삼] 2. MERN 풀스택 환경 기본세팅 - 2 (1) | 2023.02.26 |
댓글