如何从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?
两个.find
asynchronous执行的,所以你不知道什么时候(或者是否)完成。 也就是说,在尝试呈现模板之前,需要等到两个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司机。
- Bookshelf.js在创build新logging之前进行独特的电子邮件validation
- 将Express NodeJS的值传递给AngularJS控制器variables
- 在Express-JS中查找“Unexpected token;”错误的原因/行
- 在express节点上使用本地驱动程序连接到heroku上的mongodb
- 刷新浏览器后,包含“hypen”的URL不会经过angular度$ routeProvider.when(),而直接请求服务器
- Openshift无法加载c ++ bson扩展/无法find模块('swig')
- “使用Node.js进行直接响应” – 使用不同的Node.js进程发送HTTP响应(与主进程不同)
- Postgres方言不工作在续集-m
- Node.JSvalidationGoogle身份validation令牌