如何将MongoDB集合传递给.pug模板?
我有这个函数,可以获取一个名为 Test 的 mongodb 集合。
function get(req, res) {
mongo.GetSort({}, {state: 1, name: 1}, 'Test')
.then(function (list) {
res.send(list);
});
}
我将如何将其传递给哈巴狗模板?我尝试
| console.log(Test)
在哈巴狗模板中,但对象 Test 不存在。
我的目录中有test.js
和test.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
问题是,快递在引擎盖下做大多数模板。因此,使用快递可能会使它更干净。
因此,如果您有快递,则需要遵循文档: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发送到客户端浏览器(毕竟这是快速的事情(。
我错过了什么吗?