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

home2 게시판 Node.js, Express 게시판 댓글 기능에서 문제가 발생하여 남깁니다.

댓글 기능에서 문제가 발생하여 남깁니다.

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

    권희범
    참가자
    테스트용으로
        <div class="detail-bg">
          <h4><%= result.title %></h4>
          <p><%= result.connect %></p>
          <hr style="margin-top: 60px">
          <div>
            <p>작성자 댓글내용</p>
            <%= result2.writer[i]%>
          </div>
          <form action="/comment" method="POST">
            <input name="content">
            <input name="parentId" value="<%= result._id %>" style="display: none">
            <button type="submit">댓글작성</button>
          </form>
      </div>  
    해당 코드를 작성했는데 
    
    
     >> 19|         <%= result2.writer[i]%>
        20|       </div>
        21|       <form action="/comment" method="POST">
        22|         <input name="content">
    i is not defined
        at eval ("D:\\FullStack_KHB\\exam\\views\\detail.ejs":21:41)
        at detail (D:\FullStack_KHB\exam\node_modules\ejs\lib\ejs.js:703:17)
        at tryHandleCache (D:\FullStack_KHB\exam\node_modules\ejs\lib\ejs.js:274:36)
        at exports.renderFile [as engine] (D:\FullStack_KHB\exam\node_modules\ejs\lib\ejs.js:491:10)
        at View.render (D:\FullStack_KHB\exam\node_modules\express\lib\view.js:135:8)
        at tryRender (D:\FullStack_KHB\exam\node_modules\express\lib\application.js:657:10)
        at Function.render (D:\FullStack_KHB\exam\node_modules\express\lib\application.js:609:3)
        at ServerResponse.render (D:\FullStack_KHB\exam\node_modules\express\lib\response.js:1048:7)
        at D:\FullStack_KHB\exam\server.js:153:11
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    i is not defined 라는 오류창이 나와서 
    
          let result2 = await db.collection('comment').find({ parentId : new ObjectId(req.params.id) }).toArray()
          res.render('detail.ejs', {result : result, result2 : result2})
          console.log(result2);
        })
    
    이렇게 result2가 제대로된 결과를 반환하는지 console.log로 확인해보았을 때 
    
    {
      acknowledged: true,
      insertedId: new ObjectId("661e5a3ec7af2db6b4539f44")
    }
    []
    
    이렇게 빈 배열로 출력이 되고 있습니다. 저기 나오는 insertedId는 몽고 db에서 확인했을 때
    
    _id
    :  ObjectId('661e5a3ec7af2db6b4539f44')
     
    content
    : "ddddddddddddddd"
      
    writerId
    : ObjectId('660bff3164d21e4f889bb7b5')
    
    writer
    : "asdf"
    
    parentID
    : ObjectId('661e5a3ec7af2db6b4539f43
    
    이런식으로 ParentID가 아닌 댓글의 id가 console.log에서 출력이 되고 있습니다.
    
    server.js 가장 하단에 댓글을 DB에 저장하는 코드는
    
    app.post('/comment', async (req,res)=>{
      let result = await db.collection('comment').insertOne({
        content : req.body.content,
        writerId : new ObjectId (req.user._id),
        writer : req.user.username,
        parentID : new ObjectId (req.body.parentID)
      })
      res.redirect('back')
    })
    
    
    이렇게 작성 되어있습니다 
    
    
    
    #120490

    권희범
    참가자
    해당 상황으로 댓글에 DB는 잘 저장이 되는데 
    
            <% for (let i = 0; i < result2.length; i++) { %>
              <p><%= result2[i].writer %> <%= result2[i].content %></p>
           <% } %> 
    
    이 코드를 사용 시 댓글이 출력 되고 있지 않아 조건식을 활용했습니다.
    
    <% if (result2 && result2.length > 0) { %> <% for (let i = 0; i < result2.length; i++)
     
    { %> <p><%= result2[i].writer %> <%= result2[i].content %>
    
    </p> <% } %> <% } else { %> <p>댓글이 없습니다..</p> <% } %>
    
    이런식으로 댓글이 없을 때 댓글이 없습니다라고 출력하게끔 하였을 때 댓글을 불러오지 못하는지
    detail 페이지에서 댓글이 없습니다..라고 나오고 있구요
    #120550

    codingapple
    키 마스터
    댓글불러오는 코드에서 req.params.id 같은게 잘 나오고있는지 출력해봅시다
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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