2016-01-02 22 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