簡體   English   中英

Mongodb / Express / Handlebars具有res.render等到數據被拉出后

[英]Mongodb/Express/Handlebars have res.render wait until after data is pulled

似乎在從mongodb中提取數據之前,正在加載res.render。 有沒有辦法解決。

app.use('/portfolio/:item_id', function(req, res, next) {
portfolioItem.findOne({ projectID : req.params.item_id}, function (err, item){
    if (err) return handleError(err);
    if (item) {
        res.locals = {
            script: ['isotope.js'],
            title: item.projectTitle,
             projectID: item.projectID,
             projectTitle: item.projectTitle,
             projectDescription: item.projectDescription,
             projectURL: item.projectURL,
             customerName: item.customerName,
             websiteCategories: item.projectCategories,
             grid: item.grid
        }
    }}); 
    res.render('case_study'); 

});

附帶說明一下,我也使用把手。

就像snozza在他的評論中提到的那樣, res.render必須在findOne回調中。

這是由於Node.js及其異步運行的事實。 它同時運行兩個函數,並且不等待MongoDB調用中的數據返回。 在findOne函數本身內,代碼是同步運行的,因此將res.render放在第二條if語句之后即可解決問題。

app.use('/portfolio/:item_id', function(req, res, next) {
  portfolioItem.findOne({ projectID : req.params.item_id}, function (err, item){
    if (err) return handleError(err);
    if (item) {
      res.locals = {
        script: ['isotope.js'],
        title: item.projectTitle,
        projectID: item.projectID,
        projectTitle: item.projectTitle,
        projectDescription: item.projectDescription
        projectURL: item.projectURL 
        customerName: item.customerName,
        websiteCategories: item.projectCategories,
        grid: item.grid
      }
      res.render('case_study'); 
    }
  }); 
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM