2017-05-05 59 views
0

我正在創建一個博客站點,並試圖實現一個功能,以便用戶可以報告具體的評論。這個想法是,用戶將點擊特定評論下的「報告」鏈接,並將其帶到一個新頁面,該頁面將預先填入他們正在報告的評論以及評論所屬博客的標題。傳遞來自2個MongoDB對象的數據

到目前爲止我寫了下面的路線:

router.get('/blogs/:blog_id/comments/:comment_id/report', function(req, res) { 
// find comment 
Comment.findById(req.params.comment_id, function(err, foundComment){ 
if(err){ 
    res.redirect('/blogs'); 
} else { 
    res.render('report-comment', {comment: foundComment}); 
} 
}); 
}); 

這是成功地生成我的報告的評論頁面,從報告的評論頁面,我可以使用EPS <%= comment.text%>然後填充評論。但是,在這條路線上,我無法解決如何通過評論所嵌入的博客細節。在我的報告評論表單中,我希望能夠使用<%= blog.title%>填充博客標題,但我的路線中的哪個位置可以通過博客信息?

回答

0

您使用req對象將信息從一箇中間件功能傳遞到下一個中​​間件功能。你也應該指定單獨的中間件函數來檢索不同的數據,然後最終渲染它。例如您可以修改您的代碼是這樣的:現在

router.get('/blogs/:blog_id/comments/:comment_id/report', 
    function(req, res, next){ 
    // this is first middleware and fetches comment data 
    Comment.findById(req.params.comment_id, function(err, foundComment){ 
     if(err){ 
     res.redirect('/blogs'); 
     }else{ 
     req.comment = foundComment; 
     next(); 
     } 
    });//findById() 
    },  
    function(req, res, next){ 
    // this is second middleware that fetches blog data 
    Blog.findById(req.params.blog_id, function(err, foundBlog){ 
    if(err){ 
     res.redirect('/blogs'); 
    } else { 
     req.blog = foundBlog; 
     next(); 
    } 
    }); 
}, 
function(req, res){ 
    // this is third and final middleware that renders the page 
    var pageInfo = {}; 
    pageInfo.comment = req.comment; 
    pageInfo.blog = req.blog; 
    res.render("/report-template", pageInfo); 
}); 

,在report-template文件,你可以使用這些變量作爲commentblog

+0

令人驚歎!謝謝你的作品絕對完美:) – DaveB1