
오느릉 MongoDB 환경 셋팅과 데이터 저장까지 해보자!
mongodb atlas //검색 후 회원가입
무료티어 회원가입 해 주면숴
데이터베이스 만들기
Database Access
에서 데이터베이스 이름과 비밀번호를 먼저 만들어 준다.
*Built-in Role 에서 Altas admin으로 설정 해주어야 node.js 접속이 가능하다고 한다.
Network Access
에서도 ALLOW ACCESSS FROM ANYWHERE를 눌러 설정해준다.
컬렉션 만들기
Database에서 만들어놓은 데이터베이스에 들어가 Browse Collections를 눌러 collection도 미리 만들어준다.
MongoDB 무료 호스팅 해줘. 에서 할 일은 다 끝났다.
데이터베이스에서 connect를 누르면 connec to your application을 누르면 node.js 환경에서 사용하는 예제를 알려준다.
npm install mongodb
// 3. Add your connection string into your application code 항목에서
// View full code sample 를 누르면 예제 뿅
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://DB아이디:DB비밀번호@계정어쩌고흠냐흠냐/?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
//MongoDB에서 알려준 코드샘플을 이렇게 사용했다.(어제 예제 참고) POST를 사용해 요청시에 DB에 자료를 저장한다.
app.post('/요청할경로', async (요청, 응답) => {
try {
// MongoDB 클라이언트 연결
await client.connect();
await client.db("데이터베이스명").command({ ping: 1 });
// 컬렉션에 자료 추가
const result = await client.db('데이터베이스명').collection('컬렉션명').insertOne({
title: 요청.body.title, //POST로 받은 name 값
date: 요청.body.date //POST로 받은 name 값
});
console.log('저장완료');
console.log(result);
} catch (에러) {
console.error(에러);
} finally {
// 클라이언트 연결 닫기
await client.close();
}
});
오늘은 여기까지