Express displaying mongodb documents in Jade

淺唱寂寞╮ 提交于 2019-12-06 05:18:50

https://naltatis.github.io/jade-syntax-docs/ Has useful information for view.jade files

index.js needs an array to hold the mongo results:

 var results_from_mongo = [];

and everytime we get a result from the query, let's push it onto the array (array language for "insert an element into the array")

  results_from_mongo.push(doc); //Push result onto results_array

then we must simply send it along to res.render:

  res.render('index', {"results": results_from_mongo });

So in your index.js file

/* GET home page. and iterate, display the collection to console log. */
router.get('/', function (req, res) {
    var MongoClient = require('mongodb').MongoClient
    var url = 'mongodb://localhost/EmployeeDB';

    var results_from_mongo = [];

    MongoClient.connect(url, function (err, db) {
        var str = db.collection('employee').find();
        str.each(function (err, doc) {
                console.log(doc);   
                results_from_mongo.push(doc); //Push result onto results_array
        });  

        //now we have a results array filled like this:
        // results_from_mongo = ["some string", "some string", "some string"]
       //so let's pass them to the jade file to render them.

      res.render('index', {"results": results_from_mongo });

//this will pass the data in JSON format to the JADE file called 'index' (index.jade)

The data at this point looks like

    { "results" : ["some string", "some string", "some string"] } 

and in index.jade we can do something like

extends layout

block content
h1= title
h2= "results from mongo:"
select
  each mongo_result, i in results
    div Result #{i} #{mongo_result}

The jade (now pug) file needs to be set up to show a table, if you want to send an array from the database to be displayed as html. Here is the relevent code that I use for my table layout in a sample index.pug file.

table
    thead
      tr
        th Flight Date
        th Tail Number
        th Origin
        th Destination
        th Dep
        th Arr
    tbody
      each mongo_result, i in results
        tr
          td= mongo_result.flight_date
          td= mongo_result.tail_num
          td= mongo_result.origin_airport_code
          td= mongo_result.dest_airport_code
          td= mongo_result.dep_time
          td= mongo_result.arr_time

In this example, under the table header thead, I am setting up the captions for the header row of the table. Then under tbody, I am specifying the actual data I want pug to pull from each row of the array that is pushed to it. Pug is very sensitive to indentation with white space characters: it requires it. So you need to pay close attention to indentation or the results won't work as expected.

You can use the db() method to handle the collection:

var data = [];

router.get('/', function (req, res) {
    var MongoClient = require('mongodb').MongoClient;
    var url = 'mongodb://localhost:27017/';   // do not put db in url, EmployeeDB
    MongoClient.connect(url, function (err, db) {
        if (err) throw err;
        var dbo = db.db("EmployeeDB");
        dbo.collection("employee").find({}).toArray(function(err, result) {
            if (err) throw err;
            data = result;
            db.close();
            });
        }); 
        res.render('index',{ data_employee : data });
    });
});

And you must update your index.jade (or index.pug) file:

extends layout

block content
  div.main
    table
      thead
        tr
          th name
          th surname
      tbody
        each data in data_employee
          tr
            td= data.name
            td= data.surname
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!