유튜브컨텐츠탐색-StelLife/MongoDB
프로젝트(2) - MongoDB 연결
sakuraop
2023. 2. 8. 16:48
MongoDB 연결
Atlas DB만들기
https://sakuraop.tistory.com/407
터미널에서 MongoDB 설치하기
$ npm i mongodb@3.6.4
server.js (서버 파일)에서 다음 코드를 입력하기
const mongoUri = process.env.REACT_APP_DB_ACCESS;
const mongoUri = "mongodb+srv://디비계정아이디:디비계정패스워드@cluster0-qaxa3.mongodb.net/데이터베이스이름?retryWrites=true&w=majority";
=> 주소를 변수에 담고
const { MongoClient } = require("mongodb");
=> MongoClient 모듈을 불러오고
const client = new MongoClient(mongoUri, { useUnifiedTopology: true });
=> MongoClient 객체 생성. 두번째 인자는 크게 신경 쓸 필요 없는 warning을 없애준다고 함
let db;
client.connect((에러) => {
if (에러) return console.log(에러);
db = client.db("test");
app.listen(PORT, () => {
console.log(`${PORT} 포트 서버 실행. Database에 연결 되었음`);
});
});
=> db에 연결을 하고, express server 실행