본문 바로가기
Frontend/Project(개인 기록용)

MongoDB에 저장된 DB가져와서 화면에 보여주기

by Johnny_gon 2023. 6. 2.
728x90
반응형

server 작업 코드

 

mongoDB에서 다큐먼트를 찾는 명령어인 find()를 사용하여 저장된 doc를 찾습니다.

성공시 success : true와 함께 불러온 doc 전체를 postList이름으로 client에 보냅니다.

 
  app.post("/api/post/list", (req, res) => {
    //DB에 저장된 데이터 불러오기
    Post.find()
      .exec()
      .then((doc) => {
        res.status(200).json({ success: true, postList: doc });
      })
      .catch(() => {
        res.status(400).json({ success: false, text: "DB불러오기 실패" });
      });
  });
 

 

 

 

find()는 공식문서를 보면 아래처럼 사용할 수 있다고 합니다.

추가로 find(옵션추가) 를 통해서 조건을 걸어 데이터를 가져올수 있다고 하네요😊

Find All Documents in a Collection

The find() method with no parameters returns all documents from a collection and returns all fields for the documents. For example, the following operation returns all documents in the bios collection:

db.bios.find()

 

find()관련 MongoDB 공식문서
참조  https://www.mongodb.com/docs/manual/reference/method/db.collection.find/

 

db.collection.find() — MongoDB Manual

Docs Home → MongoDB Manual db.collection.find(query, projection, options)mongosh MethodThis page documents a mongosh method. This is not the documentation for database commands or language-specific drivers, such as Node.js.For the database command, see t

www.mongodb.com

 

 

 

 

exec()를 사용할 때와 안 할 때에 결과 값은 같은데 사용하는 이유가 궁금해서 찾아보았다.
사용 이유는 온전한 promise를 반환값으로 얻고, 에러 발생하면 stack trace에
오류가 발생한 코드의 위치가 포함된다고 사용을 권장한다고 합니다...  그럼 사용!!


출처 https://tesseractjh.tistory.com/166
promise관련 참고  https://www.zerocho.com/category/MongoDB/post/59b6228e92f5830019d41ac4

 

(MongoDB) Mongoose(몽구스) 프로미스

안녕하세요. 이번 시간에는 몽구스로 프로미스(promise)를 사용하는 방법에 대해 알아보겠습니다. 기본적으로 몽고DB(노드용 드라이버)는 콜백으로 결과값을 반환합니다. 콜백은 간단하지만, 다들

www.zerocho.com

 

[mongoose] exec()은 어떤 역할을 하는가?

아래 사진은 mongoose 공식 문서에서 find 메서드에 대해 설명하고 있는 부분이다. 그런데 사용 예시에서 어떤 때에는 exec()을 사용하고, 어떤 때에는 exec()을 사용하고 있지 않다. exec()을 사용하고

tesseractjh.tistory.com

     

 

 

client 작업 코드

 

페이지 렌더링(마운트)시에 한번만 실행하려고 useEffect훅에 담아서

서버 쪽에서 보낸 res 데이터를 확인해봅니다.

 
  useEffect(() => {
     //useEffect안에 넣은 이유 컴포넌트 렌더시 코드실행
     axios.post("/api/post/list").then((res) => {
       console.log(res.data.postList);
     });
   }, []);
 

 

 

잘 출력 되네요

DB에 저장된 전체 data 가져오기 성공!!

 

 

 

이제 server쪽에서 받은 데이터를 화면에 출력하는 작업을 해봅니다.

res 데이터 담을 state 선언하고.. 배열로 담을거라 초기 state에 [ ]넣어줘야 에러가 안나요..

 

콘솔로 확인 결과 

빈 배열이였다가 axios통신이 끝나고 데이터가 채워지네요..

 
 const [postList, setPostList] = useState([]);
  useEffect(() => {
    axios
      .post("/api/post/list")
      .then((res) => {
        setPostList(res.data.postList);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);
 

 

 

 

map()을 사용해서 데이터 title content 하나하나 출력해줍니다

결과는...

 
  return (
    <>
      <h2>리스트 컴포넌트</h2>
      {postList.map((list, i) => {
        return (
          <div key={i}>
            <p>{list.title}</p>
            <p>{list.content}</p>
          </div>
        );
      })}
    </>
   );
 

 

출력 성공!!

 

 

728x90
반응형