2016-01-02 15 views
1

我有一個簡單的應用程序,它使用Express和Hoffman視圖引擎來流式傳輸視圖。使用Mongoose的Dust.js流式視圖

我目前正在嘗試擴展由官方Dust.js存儲庫提供的an example

不幸的是,我不能使它使用Mongoose進行數據檢索。

app.js

var app = express(); 

app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'dust'); 
app.engine('dust', hoffman.__express()); 

app.use(hoffman.stream); 

app.get('/', function (req, res) { 
    res.stream("hello", { 
    "test": function(chunk, context, bodies, params) { 
     //This works as expected 
     //return [{name:"This is a name"},{name:"This is another name"}]; 

     return model.find().lean().exec(function(err, docs) { 
       return docs; 
      }); 
    }, 
    "test1": function(chunk, context, bodies, params) { 
     return modelB.find(function(err, docs) { 
       return docs; 
      }); 
    } 
    }); 
}); 

hello.dust

{#test} 
    <br>{name} 
{/test} 

{#test1} 
    <br>{name} 
{/test1} 
+0

'model.find()'的輸出是什麼?如果你登錄它或什麼的。這是一組文件? – Interrobang

+0

你好@Interrobang,新年快樂。 我的模型返回一個文檔數組。 例如 '[{ _id:5687 cf282018e4df73b62ea8, 名: '插入1451740968750', __v:0 },{ _id:5687 cf282018e4df73b62ea9, 名: '插入1451740968750', __v:0 }] ' – Theodore

回答

1

我認爲這個問題是您的.find使用。 Mongoose將用文檔調用Mongoose docs show that you must have a callback,因爲.find不是同步的。

您正在返回.exec的返回值,這似乎是一個承諾。

望着貓鼬源,如果你傳遞一個回調.exec,它就會resolve the Promise with nothing

if (!_this.op) { 
    callback && callback(null, undefined); 
    resolve(); 
    return; 
} 

你有幾個選項,通過一個輔助異步數據傳遞到灰塵。首先,你可以從助手中返回一個Promise或者Stream,這個Dust會正確的讀取。爲此,貓鼬提供Query#stream

var stream = Thing.find({ name: /^hello/ }).stream(); 

否則,您可以手動渲染到塵埃chunk在貓鼬的回調:

"test": function(chunk, context, bodies, params) { 
    return chunk.map(function(chunk) { 
    model.find().lean().exec(function(err, docs) { 
     chunk.section(docs, context, bodies); 
     chunk.end(); 
    }); 
    }); 
}, 

我不使用貓鼬,所以如果有一個選項做同步的發現,我們可以看看這更多。

+0

你好,可愛的答案。我找不到任何文件指出塊如何工作。 感謝您的回答:) – Theodore

+1

[上下文助手](http://www.dustjs.com/guides/context-helpers/)詳細介紹了大塊。我認爲從輔助程序返回Stream對於您來說會更快/更輕鬆,尤其是如果您使用Hoffman streaming。 – Interrobang

+0

我已經使它的工作,只是一個更簡單的問題是有可能崩潰的流和重定向我的應用程序到404頁,如果我的一個功能未能執行? – Theodore