2014-07-26 3 views
-1

나는 node.js와 MongoDB를 처음 접했으므로 나와 함께 부담해야한다. 나는 MongoDB 컬렉션에 세부 사항을 저장하는 폼을 가지고있다; 그런 다음 .findOne (지금은)을 사용하여 쿼리합니다. 기본적으로이 값을 내 index.ejs 파일로 전달하고 테이블의 일부로 표시하려고합니다. 따라서 표가 나타나야합니다 :MongoDB 문서 값을 통해 EJS 테이블로 전달

이름 : 웹 브라우저의 Connor.

데이터베이스를 쿼리에 대한 나의 코드 :

router.get('/', function(req, res) { 
    res.render('admin/index'); 

    MongoClient.connect("mongodb://localhost:27017/tickets", function(err, db) { 
     // Ensure we have connected 
     if(err) { 
      console.log("Cannot connect to database"); 
     } else { 
      console.log("Connected to database"); 
     } 
     // Create a collection to query 
     var collection = db.collection('tickets'); 
     collection.findOne({name:String}, function(err, item) { 
      // Ensure we have found the ticket 
      if(err) { 
       console.log("There was a problem finding the ticket."); 
      } else { 
       console.log("Ticket found!"); 
      } 
     }); 
    }); 
}); 

테이블 생성 내 코드 : 당신이 검색 한 후 문서를 페이지를 렌더링하는 경우

<table> 
    <thead> 
     <tr> 
      <th>Name</th> 
      <th>Email</th> 
      <th>Subject</th> 
      <th>Message</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td></td> 
      <td></td> 
      <td></td> 
      <td></td> 
     </tr> 
    </tbody> 
</table> 

답변

16

것은 다음 문서를 전달할 수를 또는 일부 속성을 템플릿에 추가하려면 다음과 같이하십시오. 너는 findOne()에 콜백에 넣어 그것을 시도 할 수 있습니다. 더 많은 정보를 원하는 경우

<td> 
    <%= name %> 
</td> 

, 당신은 this tutorial 좀보고 할 수 있습니다 : 다음과 같이

res.render('admin/index', { name: item['name'] }); 

그런 다음 당신은 당신의 EJS 템플릿에서 액세스 할 수 있습니다.

+1

나는 JS에 정통한 것은 아니지만 코드 숨김에서 벗어난'{'이있다 : 오타가 될 수 있는가? –

+0

@MatthieuM., 절대적으로. 오타 였고 수정되었습니다. 그것을 지적 주셔서 감사합니다! –