Search code examples
node.jsmongodbpug

Iterate Mongodb Collection in pug/jade template


How do you pass a MongoDB collection to a .pug template?

I have this function that gets a mongodb collection named Test.

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

How would I pass this to a pug template? I try to

| console.log(Test) in the pug template but the object Test does not exist.

I have test.js and test.pug in my directory. I tried searching for my question but most results involved using Express.js. Thank you


Solution

  • I do not know where you get GetSort from? or what a Tailwater is? and you say without involving Express (because function get(req, res){ res.send(... sure looks like a signature express function, so you have me a little bit confused.)

    Anyway, here is the simplest example I could come up with without any hint of 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();
        });    
    });
    

    And a template.pug along those lines:

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

    The thing is, express does most templating under the hood. So using express would likely make it cleaner.

    So if you have express, you want to follow the documentation: 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 });
    })
    

    This would do the same thing as the example above AND ALSO send the html to the clients browser (which is express' thing after all).

    Did I miss something?