[MongoDB] MongoDB Mongoose에 연결하면서 발생한 에러

Shin Hyun Woo·2022년 12월 1일
1
post-thumbnail

John-Ahn님 강의인 '따라하며 배우는 노드, 리액트 시리즈 - 기본 강의'를 들으면서 발생했던 에러이다.

파일에 아래의 코드처럼 작성하였다.

const express = require("express");
const app = express();
const port = 3000;

const mongoose = require("mongoose");
mongoose
  .connect(
    "mongodb+srv://<username>:<password>@cluster0.3rt3shc.mongodb.net/?retryWrites=true&w=majority",
    {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
      useFindAndModify: false,
    }
  )
  .then(() => console.log("MongoDB connected"))
  .catch((err) => console.log(err));

app.get("/", (req, res) => {
  res.send("Hello World! 안녕하세요!");
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

발생상황

몽고DB 세팅을 마치고 mongoose에 연결하기 위해 위의 코드를 작성했으나 아래의 에러 발생

MongoParseError: options usecreateindex, usefindandmodify are not supported

에러문을 보면 options인 usecreateindex, usefindandmodify는 지원하지 않는다라는 에러!

문제 해결

어떻게 해결하면 되는지 찾아보니 이런 문제를 겪은 사람이 꽤 있었다보다.

useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported options. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. Please remove these options from your code.
출처 : stackoverflow

Mongoose 버전이 6.0 이상이면 useNewUrlParser, useUnifiedTopology, useFindAndModifyuseCreateIndex는 더 이상 지원되지 않는 옵션이기 때문에 제거하라는 해결방법이다.

왜냐하면 Mongoose 버전 6.0 이상부터는 기본적으로 useNewUrlParser, useUnifiedTopology, useFindAndModifytrue, useCreateIndexfalse로 동작하기 때문이다.

현재 내가 설치한 Mongoose는 6.7.5 버전이기 때문에 위의 코드를 제거하면 이 에러를 해결할 수 있다.

const express = require("express");
const app = express();
const port = 3000;

const mongoose = require("mongoose");
mongoose
  .connect(
    "mongodb+srv://username:<password>@cluster0.3rt3shc.mongodb.net/?retryWrites=true&w=majority"
  )
  .then(() => console.log("MongoDB connected"))
  .catch((err) => console.log(err));

app.get("/", (req, res) => {
  res.send("Hello World! 안녕하세요!");
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

도움받은 링크 : lee951109님 Velog게시글

+ 이어서 발생한 문제...

발생 상황

Mongoose에 연결하기 위해 몽고DB의 URI를 했지만 에러가 지속적으로 발생했다...
몽고DB URI에 password에 특수문자를 이용해서 인코딩이 되면서 발생한 문제이다.

const express = require("express");
const app = express();
const port = 3000;

const mongoose = require("mongoose");
// password 부분에 특수문자인 '@'를 이용해서 발생했다.
mongoose
  .connect(
    "mongodb+srv://username:<password@>@cluster0.3rt3shc.mongodb.net/?retryWrites=true&w=majority"
  )
  .then(() => console.log("MongoDB connected"))
  .catch((err) => console.log(err));

app.get("/", (req, res) => {
  res.send("Hello World! 안녕하세요!");
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
MongoParseError: URI does not have hostname, domain name and tld

URL에 hostnamedomain nametld가 없다라는 의미인데...
아직 아무것도 모르고 따라쳐보는 수준이기 때문에 또 구글링..!

문제 해결

Solution-1: If you are using any special character in your password you need to encode the particular character as %+ASCII_code_of_the_character below link explains everything.
공식 홈페이지 참고 링크

Solution-2: Click on auto-generate password and paste it into the connection string, it will work.
출처 : stackoverflow

첫번째 해결 방안

만약 password에 특수문자를 사용하는 경우 특수문자를 인코딩이 필요하다. 공식 홈페이지 링크를 참고하여 수정하는 방법이다.

위에서 usernamepassword를 인코딩하기위해 encodeURIComponent 함수를 사용하여 인코딩해준 후 몽고DB URI에 백틱을 이용한 '템플릿 리터럴'을 사용하여 작성해주도록 하자!

const username = encodeURIComponent("<username>")
const password = encodeURIComponent("<password>")
const express = require("express");
const app = express();
const port = 3000;

// 특수문자가 있다면 encodeURIComponent 함수로 인코딩 후..
const username = encodeURIComponent("<username>")
const password = encodeURIComponent("<password>")

const mongoose = require("mongoose");

// 템플릿 리터럴로 값을 문자열에 넣는다.
mongoose
  .connect(
    `mongodb+srv://${username}:${password}@cluster0.3rt3shc.mongodb.net/?retryWrites=true&w=majority`
  )
  .then(() => console.log("MongoDB connected"))
  .catch((err) => console.log(err));

app.get("/", (req, res) => {
  res.send("Hello World! 안녕하세요!");
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

성공적으로 URI 연결하는 부분의 then 메서드에 작성한 'MongoDB connected' 로그가 출력이 되었다! 👍

두번째 해결 방안

첫번째 해결방안으로 해결했다고 안해보면 손해!

두번째 방법은 몽고DB에서 비밀번호를 직접 수정하거나 자동으로 생성하면 된다.

아래의 SECURITY 탭에서 Database Access로 접속하고,

Database Users 탭의 User 리스트에서 EDIT 버튼을 클릭하면

새로운 창이 뜨면서 Password Authentication 메뉴에 Edit Password 탭을 눌려서 password를 특수문자 없이 수정하면 된다.

만약 다시 생성하는 것이 번거롭다면 아래의 Autogenerate Secure Password 버튼을 눌려 자동 생성해주고 password를 기억해두면 된다.

도움받은 링크 : stackoverflow

profile
untiring_dev - Notion 페이지는 정리 중!

1개의 댓글

comment-user-thumbnail
2023년 9월 30일

자세한 설명 감사합니다!

답글 달기