1. mongodb 사이트 접속
MongoDB: The Developer Data Platform
Get your ideas to market faster with a developer data platform built on the leading modern database. MongoDB makes working with data easy.
www.mongodb.com
2. start Free 버튼 클릭
3. sign up (간단히 sign up with google로 가입함)
4. 개인보호 정책 동의
체크박스 체크 후 submit
5. 질문사항 답변
finish 클릭
6. 중요!
반드시 M0 free 클릭
그래야 무료로 사용가능
나머지 Region이나 Name은 자유롭게 선택, 입력 가능
7. username과 허용가능한 IP Address 입력
1. authenticate connection 연결 인증
username은 자유롭게 이름을 입력하고
password도 자유롭게 입력하되, autogenerate Secure Password로 랜덤한 패스워드를 생성하여 사용 가능
추후 연결할 url에서 password를 입력하여 사용할 것임
create User 초록색으로 변하면 클릭
2. enable access for network 네트워크 접근 허용
Add my Current IP Address 클릭 (현재 나의 집 IP를 추가함)
Add Entry 초록색으로 변하면 클릭
맨 하단에 Finish and Close 초록색으로 변하면 클릭
8. 다음 화면으로 넘어감
중간 부분에 내가 입력한 파란색 db명 클릭
나의 경우 연두색 동그라미 옆에 Cluster0
마우스 hover하면 손가락모양으로 바뀌고
검정색 물풍선이 뜸
'Click to go to the overview page'
그 옆 Connect버튼 클릭
아래의 모달창이 뜸
여기서 나의 경우 vs code 클릭
3번에 나온 url을 복사함
9. mongodb에 connect하는 로직 입력
//mongodb
//mongodb import하기
const mongodb = require("mongodb");
//mongoclient에 연결
const MongoClient = mongodb.MongoClient;
//mongo db에 연결하는 로직
const mongoConnect = (callback) => {
//클라이언트를 이용해 mongodb 데이터베이스에 연결
MongoClient.connect(
"mongodb+srv://jenner:<password>@cluster0.7lqdxbj.mongodb.net/test?retryWrites=true"
)
.then((result) => {
console.log("connected!");
callback(result);
})
.catch((err) => console.log(err));
};
//app.js와 연결하기 위해
module.exports = mongoConnect;
해당 mongoConnect를 require해와서 원하는 파일에서 데이터를 저장할 수 있게 됨
mongoConnect에 callback을 인수로 넘기면
mongodb 내부에서 callback함수를 실행할 수 있게 됨.
const mongoConnect = require("../util/database");
class Product {
constructor(title, price, description, imageUrl) {
this.title = title;
this.price = price;
this.description = description;
this.imageUrl = imageUrl;
}
//mongodb에 연결하여 product저장하기
save() {
}
}
이 부분에 나의 아이디 : password입력해야함 특수문자등 빼먹지 않도록 유의하자. 오류남
MongoClient.connect(
"mongodb+srv://jenner:<password>@cluster0.7lqdxbj.mongodb.net/test?retryWrites=true"
)
아까 처음 생성할 당시 랜덤생성 혹은 입력했던 username과 password임
만일 잊어버렸으면 왼쪽 nav바에서 SECURITY 안의 Database Access를 클릭하면 다시 생성할 수 있음
오른쪽 EDIT버튼 클릭
password탭에서 Edit Password 클릭
Autogenerate Secure Password클릭 후 Copy 클릭
Url에 해당 password와 위의 username입력하기
그런데 여기서 그냥 연결하려고 하면 아래와 같은 에러가 날 것이므로
network에
0.0.0.0을 입력하여 또 추가하기
만약 그렇게 하고 조금 지난 뒤 다시 실행했는데 되지 않으면
nav바에서 SECURITY 안의 Database Access에서 password를 다시 autogenerate한뒤
url에 다시 입력해 주었더니 에러가 해결되었다.
10. app.js에서 서버에 연결하기
module.exports 했던 mongoConnect를 사용하여
app.listen으로 서버에 연결해보자.
console.log(client)를 하여 에러문구가 뜨지 않고 잘 연결되면 성공!
const mongoConnect = require("./util/database");
mongoConnect((client) => {
console.log(client);
app.listen(3000);
});
'공부기록 > Mongodb' 카테고리의 다른 글
[mongoose]초기 설정 (0) | 2023.10.05 |
---|---|
mongodb 툴 compass 설치하기 (Ubuntu)와 초기설정 (0) | 2023.04.14 |