我正在学习Node,Express,Jade& MongoDB的。我无法在玉器中显示我的mongodb文件。我无法自己解决这个问题。我使用console.log成功记录所有文档,并正确显示所有文档。请不要猫鼬或其他解决方案。只是如何构建此代码。我已经连接到db,显示终端中的所有文件。如何将它传递给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
答案 0 :(得分:1)
https://naltatis.github.io/jade-syntax-docs/包含view.jade文件的有用信息
index.js需要一个数组来保存mongo结果:
var results_from_mongo = [];
每当我们从查询中得到结果时,让它将它推到数组上(&#34的数组语言;在数组中插入一个元素")
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'的JADE文件。 (index.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}
答案 1 :(得分:1)
如果要从数据库发送数组以显示为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下,我指定了我想要的pug从推送到它的数组的每一行拉出的实际数据。帕格对具有空白字符的缩进非常敏感:它需要它。因此,您需要密切关注缩进,否则结果将无法按预期工作。
答案 2 :(得分:1)
您可以使用db()方法来处理集合:
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 });
});
});
并且您必须更新index.jade(或index.pug)文件:
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