I'm learning Node, Express, Jade & Mongodb. I'm unable to display my mongodb documents in jade. I'm unable to figure it out on my own. I'm successfully logging all documents using console.log and it display all the documents correctly. Please no mongoose or other solutions. Just how to build on this code. I already connected to the db, displayed all documents in terminal. How to be able to pass it to Jade and display it in view.jade? Thanks.
Here is my app.js code
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;
Here is my 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');
});
});
Here is my index.jade file
extends layout
block content
h1= title
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
来源:https://stackoverflow.com/questions/39298618/express-displaying-mongodb-documents-in-jade