2013-05-16 52 views
0

我正在爲expressjs創建一個MVC,以便學習express。我在模型和視圖之間遇到了麻煩。 Git回購存在here如何在expressjs中顯示多個貓鼬搜索結果

我想顯示博客文章的列表。我正在使用自定義茉莉花視圖,結合貓鼬和expressjs。我不知道如何返回查詢中的帖子列表(查找({})並將該對象轉移到視圖中,或者一旦擁有它們就可以在茉莉花中使用這些帖子。

我不得不訪問的最佳想法這些信息在我看來是通過res.locals,但它似乎並沒有工作。

// read 
app.get('/', function(req, res){ 
    Blog.find({},function(err, records){ 
    res.locals.posts = records 
    // res.send(records); 
    records.forEach(function(record){ 
     console.log(record["body"]) 
    }); 
    }); 

    res.render("home.jade", {online:req.online.length + ' users online', posts:VARIABLE_I_AM_UNCLEAR_ABOUT}); 
}); 

我可以看到在我的console.log正文,所以它明確我有JSON的博客文章。此外,我可以返回JSON與res.send(記錄)。我想訪問這些記錄,所以我可以在茉莉花風格的那些我認爲。

回答

2

只要將render到您試過send位置:

app.get('/', function(req, res){ 
    Blog.find({},function(err, records){ 
    res.render("home.jade", { 
     online : req.online.length + ' users online', 
     posts : records 
    }); 
    }); 
}); 

Blog.find()是異步的,所以只有當結果被送到從數據庫返回的回調函數將被調用。在你原來的情況下,你沒有先等待結果就渲染了模板。

+0

謝謝!我花了一個小時左右 –