如何从mongodb查询传递几个variables到玉tpl

//posts var docs, cats; var db = req.db; var catcollection = db.get('catcollection'); var postcollection = db.get('postcollection'); // find all post postcollection.find({},{},function(e,docs){ console.log('posts ---> '+util.inspect(docs)); }); // end find all post catcollection.find({},{},function(e,catss){ cats=catss; console.log('cats --> '+util.inspect(cats)); //<<<---- write objects from mongo }); // end find all cats for select res.render('newpost', { posts : docs, cats:cats, title: 'Add New post'}); }); **//<<<---it didn't passing the cats:cats and post vars to jade ** 

玉模板

 extends layout block content h1= title form#formAddPost(name="addpost",method="post",action="/addpost") input#inputPostTitle(type="text", placeholder="posttitle", name="posttitle") textarea#inputPostTitle(placeholder="postdesc", name="postdesc") textarea#inputPostTitle(placeholder="posttext", name="posttext") select#selectPostCats(placeholder="postdesc", name="posttext") each cat, i in cats option(value="#{cat._id}") #{cat.titlecat} button#btnSubmit(type="submit") submit ul each post, i in posts li= i+" " a(href="/editpst/#{post._id}")=#{post.title} 

我在玉tpl中得到这个错误信息无法读取未定义的属性“长度”

但如果我写了

  catcollection.find({},{},function(e,catss){ cats=catss; console.log('cats --> '+util.inspect(cats)); **res.render('newpost', { cats:cats, title: 'Add New post'});** }); // end find all cats for select 

它通过类别列表玉,但我不能通过邮件列表玉。 如何通过几个variables(职位和猫)玉tpl?

两个.findasynchronous执行的,所以你不知道什么时候(或者是否)完成。 也就是说,在尝试呈现模板之前,需要等到两个callback都被调用。

在你当前的实现中最简单的方法是嵌套一切:

 postcollection.find({},{},function(e,docs){ // handle errors catcollection.find({},{},function(e,cats){ res.render('newpost', { posts : docs, cats:cats, title: 'Add New post'}); }); }); }); 

但是,您可以同时执行这些查询,因为它们不依赖于对方。 最好的方法是使用承诺。

 Promise.all([postcollection.find(), catcollection.find()]) .then(function (docs, cats) { res.render('newpost', { posts : docs, cats:cats, title: 'Add New post'}); }); }); 

这假定.find返回一个承诺。 它应该为当前的Mongo司机。