내일배움캠프

미니프로젝트 mongodb에서 데이터 넣기, 가져오기

Neda 2023. 5. 11. 23:32

5월 11일

1. 폼 데이터를 서버로 보내기

사용자는 메인 페이지에서 영화를 검색해 해당 영화의 코멘트 페이지로 이동

-> 팀원이 만든 코멘트 페이지에서 코멘트를 입력 후 서버로 FormData 전송

-> 서버에서 FormData를 받아 mongodb로 insert()

작성자 이름, 코멘트, 별점은 input에서

나머지는 코멘트 페이지 로드 시 가져왔던 해당 영화 정보에서 가져온다.

장르는 일반적으로 2개 이상이므로, 리스트로 보낸다.

//comment.html
function posting() {
    const name = document.querySelector("#name").value;
    const comment = document.querySelector("#comment").value;
    const star = document.querySelector("#star").value;
    const movieTitle = movie.title;
    const moviePoster = movie.poster_path;
    const movieGenres = movie.genres;

    const formData = new FormData();
    formData.append("name", name);
    formData.append("comment", comment);
    formData.append("star", star);
    formData.append("movie_id", "{{id}}");
    formData.append("movie_title", movieTitle);
    formData.append("movie_poster", moviePoster);
    movieGenres.forEach((genre, index) => {
        formData.append(`genres[${index}][id]`, genre.id);
        formData.append(`genres[${index}][name]`, genre.name);
    });

    fetch("/api/comment", { method: "POST", body: formData })
        .then((res) => res.json())
        .then((data) => {
            alert(data["msg"]);
            listing();
    });
}

 

2. 서버에서 데이터 받아 저장하기

일반 문자열은 request.form[]을 통해서 받고

리스트인 장르는 while 문을 통해 모두 가져와 합친다.

그 후 insert_one() 함수로 데이터를 저장한다.

@app.route("/api/comment", methods=["POST"])
def create_comment():
    name = request.form['name']
    comment = request.form['comment']
    star = request.form['star']
    movie_id = request.form['movie_id']
    movie_title = request.form['movie_title']
    movie_poster = request.form['movie_poster']
    movie_genres = []
    index = 0
    while True:
        genre_id = request.form.get(f'genres[{index}][id]')
        genre_name = request.form.get(f'genres[{index}][name]')
        if genre_id is None or genre_name is None:
            break
        movie_genres.append({'id': genre_id, 'name': genre_name})
        index += 1
    print(movie_genres)
    doc = {
        'name': name,
        'comment': comment,
        'star': star,
        'movie_id' : movie_id,
        'movie_title': movie_title,
        'movie_poster': movie_poster,
        'movie_genres' : movie_genres
    }
    result =  db['comment'].insert_one(doc)
    print(result)
    return jsonify({'msg': '저장 완료'})

 

3. 클라이언트에서 데이터 가져오기

코멘트 페이지에서 해당 페이지의 영화에 대한 id 값 {{id}}를 통해

서버로 comment를 요청한다.

받아온 코멘트 리스트를 반복문을 통해 각각 html요소로 만들어 넣는다.

      function listing() {
        fetch("/api/comment/{{id}}")
          .then((res) => res.json())
          .then((data) => {
            commentList.innerHTML = "";
            data["result"].forEach((item) => {
              const name = item.name;
              const comment = item.comment;
              const star = item.star;
              const star_repeat = "⭐".repeat(star);

              const temp_html = `
                <div class="card-body">
                  <blockquote class="blockquote mb-0">
                    <p>${comment}</p>
                    <p>${star_repeat}</p>
                    <footer class="blockquote-footer">${name}</footer>
                  </blockquote>
                </div>
              `;
              const card = document.createElement("div");
              card.innerHTML = temp_html;
              commentList.appendChild(card);
            });
          });
      }

 

4. 서버에서 데이터 내려 보내기

요청받은 id값을 통해 mongodb에서 해당 아이디 값과 일치하는 코멘트만 가져와서 응답으로 보낸다.

@app.route("/api/comment/<int:id>", methods=["GET"])
def get_comments(id):
    all_comments = list(db.comment.find({'movie_id':str(id)}, {'_id': False}))

    return jsonify({'result': all_comments})