///
Search
🏙️

09.NodeJS 에서 MongoDB 연결하기

이전 자료

출처

rest-api 폴더 만들기
cmd 창에 아래의 명령어를 순서대로 입력하기
명령어
cd .\rest-api\ npm init --y npm install express mongoose
JSON
복사
설명
1.
cd .\rest-api\ : 일반적으로 작성할 때 cd res까지만 쓰고 키보드 tab키 누르면 자동 완성 된다. 이 명령어는 rest-api 폴더안으로 들어가기 위해서 쓰는 명령어이다.
2.
npm init —y : package.json을 만들어 주는 명령어 이다.
3.
npm install express mongoose : express 와 mongoose 모듈을 설치하는 명령어 이다.
실행화면
PS C:\Users\glory\Desktop\nodejsproject> cd .\rest-api\ PS C:\Users\glory\Desktop\nodejsproject\rest-api> npm init --y Wrote to C:\Users\glory\Desktop\nodejsproject\rest-api\package.json: { "name": "rest-api", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" } PS C:\Users\glory\Desktop\nodejsproject\rest-api> npm install express mongoose npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN rest-api@1.0.0 No description + express@4.17.1 + mongoose@5.11.18 added 81 packages from 125 contributors and audited 81 packages in 3.771s 2 packages are looking for funding run `npm fund` for details found 0 vulnerabilities PS C:\Users\glory\Desktop\nodejsproject\rest-api>
JavaScript
복사
rest-api에 server.js 파일을 만들고 아래의 코드를 입력한다.

/rest-api/server.js

const mongoose = require("mongoose"); const MONGODB_URL = "mongodb+srv://root:1234@education.driqd.mongodb.net/test?retryWrites=true&w=majority" mongoose.connect( MONGODB_URL, { useNewUrlParser: true, useUnifiedTopology:true }, (err) => { if (err){ console.log(err); }else { console.log("Connected") } } );
JavaScript
복사
코드를 입력했으면 아래의 명령어를 입력한다.
node server
JSON
복사
3번 줄에 보면 본인의 몽고디비에서 나오는 URL를 그대로 가져와서 복붙한다. (비밀번호 입력란과 디비 명 이름을 똑바로 입력할것)
mongodb+srv://root:1234@education.driqd.mongodb.net/test?retryWrites=true&w=majority
JavaScript
복사
실행화면
이 부분에서 많이 막히니 꼭 인지하고 잘 집어 넣기를 바란다. 모르겠으면 yklovejesus@gmail.com으로 연락 고고

(번외)MongoDB 접속 정보를 외부로 빼내기

variables.env 파일을 만들어서 아래와 같은 문구를 작성한다.
MONGDB_URL=mongodb+srv://root:1234@education.driqd.mongodb.net/glory_database?retryWrites=true&w=majority
JSON
복사
예시화면
npm install dotenv 설치하기
실행화면
PS C:\Users\glory\Desktop\nodejsproject\rest-api> npm install dotenv npm WARN rest-api@1.0.0 No description npm WARN rest-api@1.0.0 No repository field. + dotenv@8.2.0 added 1 package and audited 82 packages in 1.08s 2 packages are looking for funding run `npm fund` for details found 0 vulnerabilities PS C:\Users\glory\Desktop\nodejsproject\rest-api>
JavaScript
복사
server.js 파일의 내용을 바꾼다.
const mongoose = require("mongoose"); require("dotenv").config({ path : "variables.env"});//수정된 부분 mongoose.connect( process.env.MONGODB_URL,//수정된 부분 { useNewUrlParser: true, useUnifiedTopology:true }, (err) => { if (err){ console.log(err); }else { console.log("Connected") } } );
JavaScript
복사
오류 발생
PS C:\Users\glory\Desktop\rest-api> node server C:\Users\glory\Desktop\rest-api\node_modules\mongoose\lib\connection.js:693 throw new MongooseError('The `uri` parameter to `openUri()` must be a ' + ^ MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string. at NativeConnection.Connection.openUri (C:\Users\glory\Desktop\rest-api\node_modules\mongoose\lib\connection.js:693:11) at C:\Users\glory\Desktop\rest-api\node_modules\mongoose\lib\index.js:345:10 at promiseOrCallback (C:\Users\glory\Desktop\rest-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:9:12) at Mongoose._promiseOrCallback (C:\Users\glory\Desktop\rest-api\node_modules\mongoose\lib\index.js:1135:10) at Mongoose.connect (C:\Users\glory\Desktop\rest-api\node_modules\mongoose\lib\index.js:344:20) at Object.<anonymous> (C:\Users\glory\Desktop\rest-api\server.js:4:10) at Module._compile (internal/modules/cjs/loader.js:1063:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) at Module.load (internal/modules/cjs/loader.js:928:32) at Function.Module._load (internal/modules/cjs/loader.js:769:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) at internal/main/run_main_module.js:17:47 PS C:\Users\glory\Desktop\rest-api>
JavaScript
복사
오류의 원인 경로를 잘못 했다.... MONGODB를 MONGDB라고 적은것 .. 앞으로의 환경은 아래처럼 하겠다.
MONGODB_URL=mongodb+srv://root:1234@education.driqd.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
JSON
복사
const mongoose = require("mongoose"); require("dotenv").config({ path : "variables.env"});//수정된 부분 mongoose.connect( process.env.MONGODB_URL,{ useNewUrlParser: true, useUnifiedTopology:true }, (err) => { if (err){ console.log(err); }else { console.log("Connected") } } );
JavaScript
복사