Express在Jade中显示mongodb文档 [英] Express displaying mongodb documents in Jade

查看:72
本文介绍了Express在Jade中显示mongodb文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Node,Express,Jade& Mongodb.我无法在玉器中显示我的mongodb文档.我无法自行解决.我已经成功地使用console.log记录了所有文档,并且可以正确显示所有文档.请不要猫鼬或其他解决方案.只是如何在此代码上构建代码.我已经连接到数据库,在终端中显示了所有文档.如何将其传递给Jade并在view.jade中显示? 谢谢.

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.

这是我的app.js代码

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;

这是我的index.js

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');
    });
});

这是我的index.jade文件

Here is my index.jade file

    extends layout

block content
  h1= title

推荐答案

您可以使用db()方法来处理集合:

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

并且您必须更新index.jade(或index.pug)文件:

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

这篇关于Express在Jade中显示mongodb文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆