【问题标题】:Handlebar template access to mongo collection.find() variable in a nodejsHandlebar 模板访问 nodejs 中的 mongo collection.find() 变量
【发布时间】:2014-04-30 23:17:29
【问题描述】:

我有如下的 nodejs express 脚本

app.get('/approval',function(req,res){

        db.open(function(err,db) {
        var collection = db.collection('form');
    collection.find({ contact: 'James Wong' }).toArray(function(err, docs) {
        console.log(docs); 
   /*It will  will give an output something like
      { _id: 53533045fec60bd941c04a22,
       contact: 'James Wong'} */


        res.render('approval.handlebars',{resultfind : docs});
           /*it will give an output as [object Object]

        db.close();
      });

    });

我的 console.log(docs) 输出是正确的 JSON ARRAY 格式。即

{ _id: 53533045fec60bd941c04a22,
       contact: 'James Wong'} */

但是,当我使用 res.render 在车把模板中显示它时,结果将如下所示;

[object Object]

我的模板在下面

<div>
{{resultfind}}
</div>

我想访问那些对象属性。

【问题讨论】:

  • 你的模板在哪里?
  • 给你..
    {{resultfind}}
  • 嗯,你期待什么?字符串的对象是 [object Object]。您必须明确打印其内容:&lt;div&gt; {{resultfind._id}} {{resultfind.contact}}&lt;/div&gt;
  • hmm..它没有显示任何东西......在将其更改为
    {{resultfind._id}} {{resultfind.contact}}
  • 哦,我知道为什么..它被打印为数组而不是 JSON..我已经将 toArray 替换为每个函数..它现在工作正常..谢谢老兄!

标签: javascript node.js mongodb handlebars.js


【解决方案1】:

解决了..感谢 TheShellfishMeme。

两件事要做

1) 代替 toArray function ,用每个 function 替换它。这是为了保持json格式

2) 在 html {{resulfind.contact}}

处访问 JSON 格式

干杯

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2021-07-31
    • 2018-05-31
    • 2011-10-29
    相关资源
    最近更新 更多