본문 바로가기
웹/Node.js

[MongoDB] 비밀 설정 정보 관리

by ohojee 2023. 2. 25.

local환경에서 개발 - development

배포한 후 개발 - production

 

git에 올릴 때 mongoDB의 application code같은 정보들을 그냥 올린다면 다른 사람이 이 정보를 가지고 DB를 사용할 수 있다

그렇기 때문에 그 정보들을 보호해줘야한다

 

//key.js

if (process.env.NODE_ENV === 'production') {
	module.export = require('./prod');
} else {
	module.export = require('./dev');
}


//dev.js

module.exports = {
	mongoURI: 'mongodb+srv://<user>:<password>@XXX.XXX.mongodb.net/?retryWrites=true&w=majority'
}


//prod.js

module.exports = {
	mongoURI: process.env.MONGO_URI
}

local 개발 단계에서 쓰일, 배포한 후 단계에서 쓰일 파일 각 한개씩과 그 단계를 구분해주는 key.js파일을 만든다

//index.js

const config = require('./config/key');

index.js에서 const config = require('./config/key'); 문장을 추가해준 후

mongoose.connect('mongodb+srv://<user>:<password>@XXX.XXX.mongodb.net/?retryWrites=true&w=majority', {
	useNewUrlParser: true, useUnifiedTopology: true
}).then(() => console.log('MongoDB Connected ...'))
	.catch(err => console.log(err))
mongoose.connect(config.mongoURI, {
	useNewUrlParser: true, useUnifiedTopology: true
}).then(() => console.log('MongoDB Connected ...'))
	.catch(err => console.log(err))

위 코드를 아래의 코드로 바꿔주면 된다

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.

하지만 이런 오류가 떴다
읽어보니 mongoose.connect의 첫번째 파라미터는 string이어야된다는 말인 것 같은데 난 제대로 string으로 입력했는데 왜 

검색해보니 다른 사람들이 저 에러가 떴던 이유는


1. 데이터베이스를 만들지 않아 databasename을 넣지 않아서
2. user password에 <>를 지우지 않아서

3. env파일에 문제가 있는 것 같다(추측(이 사람도 나랑 똑같은 상황인듯 .connect()안에 직접적으로 mongoDB 링크를 넣으면 작동하는데 따로 옮기면 에러 발생
4. 오타

 

알고보니 오타가 맞았다

key.js에서 .exports에서 s를 빼먹은 죄,,,

 

그리고 다른 장소에서 옮겨서 다시 실행을 해보니

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://www.mongodb.com/docs/atlas/security-whitelist/

이런 에러가 발생했는데 이는 mongoDB IP를 설정할 때 집에서 연결하는 공유기의 IP를 불러온 것 같다

그래서 IP설정에서 모든 IP를 허용한다는 의미의 0.0.0.0/0를 넣어주면 정상적으로 연결이 된다

댓글