본문 바로가기
여러가지 정보/팁

Next.js에서 - 몽고DB사용하기

by 윈백 2023. 5. 25.

next.js v13기준으로 몽고 DB를 이용해서 회원가입을 구현해 봤다.

이렇게 하는게 맞는지는 잘모르겠지만, 일단 작동은 해서 올려본다.

 

1. 일단 몽고DB를 설치해준다.

npm i mongodb

 

2. 이후 최상위 디렉토리에서 lib/ db.js를 만들어주었다.

3. db.js에 다음과 같이 코드를 짜준다.

import { MongoClient } from "mongodb";

export async function connectDatabase() {
  const client = await MongoClient.connect( 몽고DB주소 );
  return client;
}

3-1 몽고DB의 주소는 몽고db의 사이트 접속후 Database Deployments 에서 Conn

ect를 누른 후 drivers를 누르면 mongodb+srv://<username>:<password>@cluster0.어쩌고저쩌고.mongodb.net/?retryWrites=true&w=majority 이런식으로 주소가 나오는데 이걸 넣어주면 된다..

 

3-2 이후 이제 유저네임과 패스워드를 넣어주면 되는데 이건 Database Access에 들어간 후 add new eatabase user로 생성해주고 그 이름과 비밀번호를 넣어주면된다.

 

3-3 그리고 Network Access에 가서 ADD IP ADDRESS로 자신의 IP를 추가해주거나 0.0.0.0/0을 추가해준다.

 

이러면 몽고DB 준비는 끝났고 사용만 해주면 된다.

 

4. app/api/auth/route.js를 만들어 주고 다음과 같이 코드를 짜줬다.

"use server";
import { hashPassword } from "@/lib/auth";
import { connectDatabase } from "@/lib/db";

async function SignUp(req) {
  const { email, password } = req;

  const client = await connectDatabase();

  const db = client.db();

  const existingUser = await db.collection("TMDB-user").findOne({
    email: email,
  });

  if (existingUser) {
    return { message: "이미 가입된 메일입니다." };
  }

  const hashedPassword = await hashPassword(password);

  const result = await db.collection("TMDB-user").insertOne({
    email: email,
    password: hashedPassword,
  });

  client.close();
}

export default SignUp;

 

4-1 아래는 lib/auth.js의 코드인데 비밀번호는 암호화해주는 라이브러리를 이용해 함수를 만들어뒀다.

npm i bcryptjs

문자를 암호화 해주는 라이브러리

위 라이브러리를 설치해주고 아래처럼 코드를 짜준다.

import { hash } from "bcryptjs";

export async function hashPassword(password) {
  const hashedPassword = await hash(password, 12);

  return hashedPassword;
}

 

이제 회원가입 컴포넌트에서 SingUp함수에 데이터를 담아 보내주면 된다.

 

"use client";

import { useState } from "react";
import styles from "./LoginForm.module.css";
import SignUp from "@/app/api/auth/route";

export default function LoginForm() {
  const [userInfo, setUserInfo] = useState({ email: "", password: "" });

  async function submitHandler(e) {
    e.preventDefault();

    if (
      !userInfo.email ||
      !userInfo.email.includes("@") ||
      !userInfo.password ||
      userInfo.password.trim().length <= 6
    ) {
      return;
    }

    const response = await SignUp(userInfo);

    console.log("res", response);
  }

  function onChangeHandler(e) {
    const { name, value } = e.target;

    setUserInfo((pre) => ({
      ...pre,
      [name]: value,
    }));
  }
  return (
    <form className={styles.loginForm} onSubmit={submitHandler}>
      <div className={styles.loginDiv}>
        <div>
          <label className={styles.loginlabel} htmlFor="email">
            E-mail{" "}
          </label>
          <input
            className={styles.loginForm__input}
            name="email"
            value={userInfo.email}
            onChange={onChangeHandler}
            id="email"
            type="email"
          />
        </div>
        <div>
          <label className={styles.loginlabel} htmlFor="password">
            비밀번호{" "}
          </label>
          <input
            className={styles.loginForm__input}
            name="password"
            value={userInfo.password}
            onChange={onChangeHandler}
            id="password"
            type="password"
          />
        </div>
        <button className={styles.loginForm__button}>확인</button>
      </div>
    </form>
  );
}

 

이렇게 코드를 짜면 다 작동이 되긴하는데 이런식으로 코드를 짜는게 맞는지는 모르겠다.