【问题标题】:how to passing few variables from mongodb query to jade tpl如何将几个变量从 mongodb 查询传递到玉 tpl
【发布时间】:2015-09-16 13:48:02
【问题描述】:
//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}

我在 Jade 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

它将类别列表传递给翡翠,但我无法将帖子列表传递给翡翠。 如何将几个变量(帖子和猫)传递给玉 tpl?

【问题讨论】:

    标签: node.js mongodb express pug


    【解决方案1】:

    .finds 都异步执行,因此您不知道何时(或是否)其中任何一个会完成。也就是说,您需要等到 两个 的回调都被调用后,才能尝试渲染模板。

    当前实现中最简单的方法是嵌套所有内容:

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

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

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

    这假设 .find 返回一个承诺。它应该适用于当前的 Mongo 驱动程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多