1. 작업 폴더로 가서
npm install mongoose
2. bin 폴더 안의 www 파일에 들어간다
3. /app 등을 불러오는 곳에 변수 하나 정의해준다
const mongoose = require("mongoose");
const mongoose = require('mongoose');
let db = mongoose.connection;
db.on('error', console.error);
db.once("open", ()=> {
console.log("Connected to MongoDB Server");
});
mongoose.connect()
여기까지 썼나?!
그런 다음 connect 함수에는 string 이 하나 들어가야 한다
atlas site로 가서
connect 버튼을 누르고 이번에는 compass 가 아니라 두번째 application 연결로 들어간다
그러면 여기서 string이 있을 텐데 이걸 복사해서 본인 계정에 맞게 바꾸면 됨
const mongoose = require('mongoose');
let db = mongoose.connection;
db.on('error', console.error);
db.once("open", ()=> {
console.log("Connected to MongoDB Server");
});
mongoose.connect(`mongodb+srv://authuser:<password>@myfirstmap.2uz9q.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`)
백틱안에 넣어야 함
지금까지 작성한 코드
근데 이걸 그냥 그대로 깃헙에 올리면
보완상의 문제가 있을 수 있다
따라서 패스워드를 따로 빼서 만들도록 하겠음 !!!!
root위치에 config folder를 만들고 그 안에
userConfig.json 파일을 하나 만들어준다
config/userConfig.json 인셈
{
"PW" : "asdkjf"
}
그 안에 중괄호 치고 모두 큰따옴표로 묶은 password를 적음
그리고 나서 다시 bin/www로 돌아와 userconfig 파일을 가져온다
const mongoose = require('mongoose');
const userConfig = require("../config/userConfig.json");
let db = mongoose.connection;
db.on('error', console.error);
db.once("open", ()=> {
console.log("Connected to MongoDB Server");
});
mongoose.connect(`mongodb+srv://authuser:${userConfig.PW}@myfirstmap.2uz9q.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`,
{useNewUrlParser:true, useUnifiedTopology:true});
const userCOnfig ~ 으로 json을 가져왔고
백틱 안에 변수 선언으로 패스워드를 입력한다
그다음 보완을 위해 usenewurlparser, useunifiedtopology를 true설정
혹시 아래와 같은 에러가 나왔다면
nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node ./bin/www`
MongoServerError: bad auth : Authentication failed.
at MessageStream.messageHandler (/Users/a/Documents/myfirstmap/mysecondmap/secondmap/node_modules/mongodb/lib/cmap/connection.js:467:30)
at MessageStream.emit (events.js:375:28)
at processIncomingData (/Users/a/Documents/myfirstmap/mysecondmap/secondmap/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
at MessageStream._write (/Users/a/Documents/myfirstmap/mysecondmap/secondmap/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at TLSSocket.ondata (internal/streams/readable.js:726:22)
at TLSSocket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9) {
ok: 0,
code: 8000,
codeName: 'AtlasError'
}
(node:3501) UnhandledPromiseRejectionWarning: MongoServerError: bad auth : Authentication failed.
at MessageStream.messageHandler (/Users/a/Documents/myfirstmap/mysecondmap/secondmap/node_modules/mongodb/lib/cmap/connection.js:467:30)
at MessageStream.emit (events.js:375:28)
at processIncomingData (/Users/a/Documents/myfirstmap/mysecondmap/secondmap/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
at MessageStream._write (/Users/a/Documents/myfirstmap/mysecondmap/secondmap/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at TLSSocket.ondata (internal/streams/readable.js:726:22)
at TLSSocket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3501) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:3501) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
이건 패스워드를 잘못 써서 그럼
잘 확인해보소
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
Connected to MongoDB Server
이렇게 나오면 정상 :)
'웹 프로그래밍 > 코로나맵' 카테고리의 다른 글
localhost와 cors 에러.. (0) | 2021.09.13 |
---|---|
[코로나맵] GET net::ERR_ABORTED 401 unauthorized 에러 날 때 key 바꿔서 해결 (0) | 2021.09.11 |