簡體   English   中英

在Pug / Jade模板中迭代Mongodb Collection

[英]Iterate Mongodb Collection in pug/jade template

如何將MongoDB集合傳遞給.pug模板?

我有此功能,獲取名為Test的mongodb集合。

function get(req, res) {
    mongo.GetSort({}, {state: 1, name: 1}, 'Test')
        .then(function (list) {
            res.send(list);
        });
 }

如何將其傳遞給哈巴狗模板? 我試着

| console.log(Test) 哈巴狗模板中的| console.log(Test) ,但對象Test不存在。

我的目錄中有test.jstest.pug 我嘗試搜索我的問題,但大多數結果涉及使用Express.js。 謝謝

我不知道您從哪里得到GetSort 還是什么Tailwater 並且您說不涉及Express(因為function get(req, res){ res.send(...當然看起來像簽名Express函數,所以您有點困惑)。)

無論如何,這是我最簡單的例子,沒有任何暗示的提示:

const compiledFunction = require('pug').compileFile('template.pug');
require('mongodb')
  .connect('mongodb://localhost:27017/')
  .then(mongo=>{
    mongo
      .db('somedb')
      .collection('somecollection')
      .find({})
      .toArray()
      .then(list=> {
        // You just pass your data into the function
        const html = compiledFunction({list: list}); 
        console.log(html);
        mongo.close();
    });    
});

以及沿着這些行的template.pug

html
  head
    title something
  body
    each item in list
      div= item.title

問題是,表達在幕后做得最多。 因此,使用Express可能會使它更清潔。

因此,如果您有快遞要求,請遵循以下文檔: https : //expressjs.com/en/guide/using-template-engines.html

app.set('view engine', 'pug'); //Tell express you want to use pug.

app.get('/', function (req, res) {
   const list = ... // 
   res.render('template', { list : list });
})

這將執行與上面的示例相同的操作,並且還將html發送到客戶端瀏覽器(畢竟這是表達的事情)。

我錯過了什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM