• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Next.js 게시판 Next.js에서 MongoDB 사용하기 오류

Next.js에서 MongoDB 사용하기 오류

2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 글쓴이
  • #82905

    이로운
    참가자
    next.js 강좌를 끝내고 혼자 개인프로젝트를 하고 있었습니다.
    처음부터 app폴더가 없어서 당황했다가 pages폴더에 _app.js, _document.js 파일이 있어서 뭐지 하고 검색후 index.js가 메인페이지라고 하길래 진행하고 있었습니다.
    현재 회원가입, 로그인 페이지는 완성한 상태인데 게시글을 만드는 과정에서 에러때문에 4시간째 아무것도 못하고있네요...
    
    - 패키지 json -
    ```
    {
    "name": "coffee-guide",
    "version": "0.1.0",
    "private": true,
    "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
    },
    "dependencies": {
    "@next-auth/mongodb-adapter": "^1.1.3",
    "autoprefixer": "10.4.14",
    "bcrypt": "^5.1.0",
    "dom": "^0.0.3",
    "lodash": "^4.17.21",
    "mongodb": "^5.3.0",
    "next": "13.2.4",
    "next-auth": "^4.21.1",
    "postcss": "8.4.23",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^5.3.0",
    "tailwindcss": "3.3.2"
    },
    "browser": {
    "tls": false,
    "net": false,
    "dns": false,
    "fs": false
    }
    }
    
    ```
    - 노드 버전 -
    v18.16.0
    
    - 데이터베이스 코드 -
    ```
    </pre>
    <pre>import { MongoClient } from "mongodb";
    const url =
    "mongodb+srv://devrowoon:qwer1234@cluster0.kyj1vtv.mongodb.net/?retryWrites=true&w=majority";
    const options = { useNewUrlParser: true };
    let connectDB;</pre>
    <pre>if (process.env.NODE_ENV === "development") {
    if (!global._mongo) {
    global._mongo = new MongoClient(url, options).connect();
    }
    connectDB = global._mongo;
    } else {
    connectDB = new MongoClient(url, options).connect();
    }
    export { connectDB };
    ```
    database.js는 이렇게 진행하였고
    
    - 에러가 난 페이지의 코드 - 
    ```
    </pre>
    <pre>import { connectDB } from "/util/database.js";</pre>
    <pre>export default async function Home() {
    let client = await connectDB;
    const db = client.db("forum");
    let result = await db.collection("post").find().toArray();
    console.log(result);
    return <div>{result[0].title}</div>;
    }
    ```
    게시글을 올릴 페이지는 이렇게 코드 진행 하였습니다.
    서버 돌리면
    Unhandled Runtime Error
    TypeError: Cannot read properties of undefined (reading '_bsontype')
    이런 에러가 나오고
    여기서 새로고침을 하면
    
    Server Error
    Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
    This error happened while generating the page. Any console logs will be displayed in the terminal window.
    이런 에러가 나옵니다
    검색 해보니 두번째 에러는  promise를 바로 랜더링 하려고 해서 나오는 문제라고 하는데 수업 그대로 따라갈때는 문제 없었는데 무슨 문제일까요..
    useEffect로 promise를 따로 반환해야할까요?
    콘솔에 데이터는 잘 찍혀나오는 것 같습니다
    #82933

    codingapple
    키 마스터
    서버컴포넌트 등 문법은 app폴더에서만 사용가능합니다 app폴더만들거나 다시 프로젝트 설치합시다
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠