공부하는 히욤이

따라하며 배우는 노드, 리액트 시리즈 - 기본 강의 #3 몽고 DB 연결 본문

Programming/React+Node

따라하며 배우는 노드, 리액트 시리즈 - 기본 강의 #3 몽고 DB 연결

히욤이 2021. 8. 12. 03:11

Mongodb Cluster 생성

 

MongoDB 홈페이지에서 회원가입을 한다.

https://mongodb.com/

 

The most popular database for modern apps

We're the creators of MongoDB, the most popular database for modern apps, and MongoDB Atlas, the global cloud database on AWS, Azure, and GCP. Easily organize, use, and enrich data — in real time, anywhere.

www.mongodb.com

 

1. Build a Database

 

2. shared 선택

 

 

별 모양이 있는 나라 아무곳이나 선택한다

 

 

다른건 손대지 말고 Cluster Name을 변경

 

Create a new Cluster를 클릭하면 다음과 같은 database가 만들어진다.

 

 

3. Create a Database User

 

Cluster User를 생성하기 위해 connect를 누른다.

 

 

Database User의 name과 password를 입력한다.

name과 password는 mongodb 연결 할 때 사용할 것 이기 때문에 절대 까먹으면 안된다

 

User가 다 만들어졌으면 연결할 방법을 고른다.

 

4. Connect to database

connect 할 방법이 3가지가 있는데 그 중 Connect your application을 선택했다.

 

 

자신의 드라이버와 버전에 맞게 설정하고 코드를 복사한다.

 

MongoDB 연결하기

1. mongoose 설치

C:\react-node\boiler-plate> npm install mongoose

 

2. index.js 추가

connect 부분에 아까 복사해둔 url 부분을 붙여넣기하고 본인의 id와 password를 입력한다.

const express = require('express');
const app = express(); //새로운 express app 생성
const port = 5000;

const mongoose = require('mongoose');
// Error 방지
mongoose.connect('mongodb+srv://id:password@boilerplate.x04nx.mongodb.net/myFirstDatabase?retryWrites=true&w=majority', {
    useNewUrlParser : true,
    useUnifiedTopology : true,
    useCreateIndex : true,
    useFindAndModify : false
}).then(()=> console.log('MongoDB Connected...'))
.catch(err => console.log(err));


// root 디렉토리에 Hello World가 출력되게
app.get('/', (req, res) => {res.send('Hello World!')});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

 

 

3. 실행

npm run start를 하면 다음과 같은 에러가 뜬다.

MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
    at NativeConnection.Connection.openUri (C:\react-node\boiler-plate\node_modules\mongoose\lib\connection.js:846:32)
    at C:\react-node\boiler-plate\node_modules\mongoose\lib\index.js:351:10
    at C:\react-node\boiler-plate\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:\react-node\boiler-plate\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (C:\react-node\boiler-plate\node_modules\mongoose\lib\index.js:1149:10)
    at Mongoose.connect (C:\react-node\boiler-plate\node_modules\mongoose\lib\index.js:350:20)
    at Object.<anonymous> (C:\react-node\boiler-plate\index.js:7:10)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)   
    at internal/main/run_main_module.js:17:47 {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map(3) {
      'boilerplate-shard-00-01.x04nx.mongodb.net:27017' => [ServerDescription],
      'boilerplate-shard-00-02.x04nx.mongodb.net:27017' => [ServerDescription],
      'boilerplate-shard-00-00.x04nx.mongodb.net:27017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
}

 

오류 해결은 여기 참고

https://heeeyomi.tistory.com/205

 

 

[MongoDB] MonooseServerSelectionError : Could not connect to any servers in your MongoDB Atlas cluster

Node에서 mongoose를 이용해 MongoDB를 연동하려고 했는데 다음과 같은 에러가 발생했다. MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is..

heeeyomi.tistory.com

 

 

해결하고 다시 실행하면 MongoDB에 연동이 된다.