在Jade中快速显示mongodb文档

我正在学习Node,Express,Jade和Mongodb。 我无法用玉来显示我的mongodb文件。 我无法自己弄清楚。 我正在使用console.log成功logging所有文档,并正确显示所有文档。 请不要mongoose或其他解决scheme。 只是如何build立在这个代码。 我已经连接到数据库,显示在terminal的所有文件。 如何能够将其传递给Jade,并将其显示在view.jade中? 谢谢。

这是我的app.js代码

var express = require('express'); var app = express(); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // Mongodb Example http://www.guru99.com/node-js-mongodb.html var MongoClient = require('mongodb').MongoClient var url = 'mongodb://localhost/EmployeeDB'; MongoClient.connect(url, function(err, db) { //Insert data into mongodb db. If the collection doesn't exist, it will be created with the first inserted document db.collection('employee').insertOne({ number : 17, name: "aaa" }); //Updating Documents in a collection db.collection('employee').updateOne( {"name": "New Employee"}, {$set: {"name": "AA"}} ); //Deleting Documents in a collection db.collection('employee').deleteOne( { "name": "name" } ); // no need to pass a second parameter. Just the name of the field to be deleted. //Querying for data in mongodb db . var cursor = db.collection('employee').find(); cursor.each(function (err, doc) { //console.log(doc) }); console.log("connected"); db.close(); }); var routes = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(require('stylus').middleware(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app; 

这是我的index.js

  var express = require('express'); var router = express.Router() //the global str variable is accessable from anywhere and logging the db.collection but how I pass it to jade? var str = ""; /* 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'; MongoClient.connect(url, function (err, db) { var str = db.collection('employee').find(); str.each(function (err, doc) { console.log(doc); }); //How to pass the .db.collection documents to Jade? res.render('index'); }); }); 

这是我的index.jade文件

  extends layout block content h1= title 

如果要从数据库发送数组以显示为html,则需要将jade(现在为pug)文件设置为显示表。 以下是我在示例index.pug文件中用于表格布局的相关代码。

 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 

在这个例子中,在表头thead下,我设置了表头标题行的标题。 然后在tbody下,我指定了我希望从数组中推出的每一行拉出的实际数据。 帕格对空白字符的缩进非常敏感:它需要它。 所以你需要密切关注缩进或者结果不能按预期工作。

https://naltatis.github.io/jade-syntax-docs/有用的信息view.jade文件

index.js需要一个数组来保存mongo结果:

  var results_from_mongo = []; 

每次我们从查询中得到一个结果,让我们把它推到数组(数组语言“将一个元素插入数组”)

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

那么我们必须简单地把它发送到res.render:

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

所以在你的index.js文件中

 /* 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 }); 

//这会将JSON格式的数据传递给名为'index'(index.jade)的JADE文件

这一点的数据看起来像

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

在index.jade中我们可以做类似的事情

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