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

home2 게시판 Node.js, Express 게시판 findone 으로 db에서 데이터 찾은 후 브라우저에 뿌리기...

findone 으로 db에서 데이터 찾은 후 브라우저에 뿌리기...

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

    냠냠냠
    참가자

    안녕하세요.

    to do app 진행하면서 내가 쓴 글만 모아서 볼 수 있는 mytodo 페이지를 만들고 있습니다.

    server.js 에서 findone 으로 작성자 지정해서 post 를 검색했고, 콘솔에는 나오지만 페이지에는 해당 데이터가 나오지 않습니다.

    에러가 딱히 뜨지 않고 어떤 문제인지 모르겠어서 도움을 요청합니다.

     

    server.js 

    //나의 todo 리스트 뿌리기
    app.get('/mytodo', 로그인했니, function(요청, 응답){
        console.log(요청.user);
        console.log('로그인 완료 후 mytodo')
        console.log(요청.login.id);
        if(요청.user.id){
            db.collection('post').findOne({작성자 : 요청.user.id},function(에러, 결과){
                console.log('db에서 작성자 찾은 결과')
                console.log(결과);
                console.log('아이디')
                console.log(요청.user.id);
                //가져온 데이터를 ejs 파일에 넣는다
                응답.render('mytodo.ejs',{myposts : 결과});
                if(에러){return console.log(에러)};
            });
        } else{
            console.log(요청.user.id);
            console.log(요청.login.id);
            응답.send("<script>alert('로그인이 필요합니다.'); window.location.replace('/login');</script>");    }
    })

     

     

    콘솔에 찍히는 것

     

    {
    _id: new ObjectId("62495b9101106e828c96ff38"),
    id: 'love',
    pw: '$2b$10$dGbuJArd4wlGB6dWduCDGePlynIgQnauxvf8NwEOXrp7tlKL/5OP.'
    }
    로그인 완료 후 mytodo
    undefined
    db에서 작성자 찾은 결과
    {
    _id: 4,
    '작성자': 'love',
    '제목': 'test - love',
    '날짜': '2022-04-01',
    '메모': 'love 아이디',
    '우선순위': '3',
    '완료': false,
    '공개': false
    }
    아이디
    love

     

     

    mytodo.ejs

        <title>나의 할 일</title>
      </head>
      <body>

        <%- include('nav.html') %>

        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

        <h4 class="ml-2 my-3 text-center"> <%= myposts.id %> 님 할일 리스트</h4>

        <div class="container input-group mb-2">
          <input class="form-control" id="search-input">
          <button class="input-group-append btn btn-primary" id="search">검색</button>
        </div>
       
        <button class="btn btn-outline-primary complete">완료</button>
        <button class="btn btn-outline-primary doing">진행중</button>
        <button class="btn btn-outline-primary all">전체</button>

        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script>
          $('#search').click(function(){
            var 입력한값 = $('#search-input').val()
            window.location.replace('/search?value=' + 입력한값);
          });
        </script>

      <div class="container">
        <ul class="list-group">
          <% for (var i = 0; i < myposts.length; i++){ %>
          <li class="list-group-item">
            <h6>글번호 : <%= myposts[i]._id %></h6>
            <a href="/detail/<%= myposts[i]._id %>"><h4> To DO : <%= myposts[i].제목 %> </h4></a>
            <p> 마감 날짜 : <%= myposts[i].날짜 %> </p>
            <button class="btn btn-outline-primary delete" data-id="<%= myposts[i]._id %>">삭제</button>
            <button class="btn btn-outline-primary edit" data-id="<%= myposts[i]._id %>"">수정</button>
            <button class="btn btn-outline-primary complete" data-id="<%= myposts[i]._id %>"">할 일 완료</button>
          </li>
          <% } %>
        </ul>
      </div>
         
       
        <script>
          $('.delete').click(function(e){
            var 글번호 = e.target.dataset.id;
            var 지금누른거 = $(this);

            $.ajax({//ajax이용해서 서버에 새로고침 없이
              method : 'DELETE', //delete 요청을 할 것이다.
              url : '/delete', //요청할 경로에
              data : {_id : 글번호}, //데이터를 같이 보낸다
            }).done(function(결과){//요청 성공시
              console.log('삭제 성공');
              지금누른거.parent('li').fadeOut(); //fadeout애니메이션활용 선택된 li태그없애기
            }).fail(function(xhr, textStatus, errorThrown){//요청 실패시
              console.log(xhr, textStatus, errorThrown);//응답코드와 에러메시지 출력
            });
          });
        </script>
     </body>

     

     

    #31185

    codingapple
    키 마스터

    myposts 출력해보면 {} 이런 자료인데 

    이건 찾은 자료가 하나라 반복문 돌릴 필요가 없어서 그렇습니다 

    .findOne 말고 .find().toArray() 이런거 쓰면 [{}, {}, {} ... ] 이렇게 다 가져와줍니다 

    #31197

    냠냠냠
    참가자

    감사합니다!! toArray 사용해서 해당 페이지 수정했습니다!

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 호 / 개인정보관리자 : 박종흠