【问题标题】:How to render with EJS the result of a Mongodb query using Express and Node.JS?如何使用 EJS 渲染使用 Express 和 Node.JS 的 Mongodb 查询的结果?
【发布时间】:2016-05-23 09:13:59
【问题描述】:

我试图避免每次使用时都创建数据库查询 router.get("/whatever",function()...)

所以我创建了一个dbController,它通过
db.collection.find().toArray()返回一个文档数组

工作正常。 不过我在这里噎住了

router.get( "/test" , function ( req , res , err ) {
        if (err) console.dir( err );

    var categoriesArray = require ( "./Controllers/dbController" ).getCategsArray();

    console.log( "!!!!!!!!!!!!!!!" + categoriesArray );

    res.render( "hello" , {
                _: _ ,
            title: "la naiba" ,
            items: categoriesArray
        });
    });

因为虽然 console.log 显示了文档数组

[Function: next]
!!!!!!!!!!!!!!!
[ { _id: ObjectID { _bsontype: 'ObjectID', id: 'QrÑUÿY?ó#M_?' },
    categories: [ [Object], [Object] ],
    id: 'mens',
    name: 'Mens',
    page_description: 
................................

我没有在 EJS 模板中得到它

..............................................
<% _.each(items, function(topC) { %>
<li>
    <h1><%= topC.name %></h1>
..........................

title property 虽然被渲染。非常感谢任何帮助,因为我是一个完整的 n00b 并且我整晚都在努力取得进展


【问题讨论】:

    标签: node.js mongodb express underscore.js ejs


    【解决方案1】:

    要交互的名称和列表在categoriesArray中,那么你需要对categoriesArray进行交互。有点像这样:

    <% items.forEach(function (topC) { %>
        <li>  
            <h1><%= topC.name %></h1>  
        </li>                                   
    <% }) %>
    

    【讨论】:

    • 非常感谢卢卡斯!只有这个有效 &lt;% _.forEach(items, function(topC) { %&gt; 尽管下划线 docs 声明 forEacheach 的别名。我晕了
    • 很好,这是另一种方式 =]
    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2015-05-12
    • 2016-11-01
    • 2012-11-27
    • 2017-09-11
    • 2016-06-10
    • 1970-01-01
    相关资源
    最近更新 更多