简体   繁体   中英

Pass variable from JavaScript to pug

I'm experimenting with Node.js and MongoDB using an Express scaffold.

I am trying to achieve the following:

  1. Connect to MongoDB and pull a document out of a collection (this I have managed to do).
  2. Display the returned document as html (this is the bit I need help with).

My index.js file looks like this:

var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient, assert = require('assert');

/* GET home page. */
router.get('/', function(req, res, next) {
    MongoClient.connect('mongodb://localhost:27017/beetleJuice', function (err, db) {

        assert.equal(null, err);

        // assign the bugs collection to var col
        var col = db.collection('bugs');

        col.findOne({"assignee" : "John Smith"}, function (err, doc) {

            assert.equal(null, err);

            // Print the resulting document to the console
            console.log("Here is my doc: %j", doc);

            // Close the connection to the database
            db.close();
        }); 
    });

    res.render('index'); // How do I pass the doc over to index.jade?
});

module.exports = router;

My assumption was that I could pass the doc variable by doing something like:

res.render('index', doc); 

However, when I try this I get an error saying that doc is not defined.

Any suggestions on what I'm doing wrong here?

Thanks to the comment from felix the solution is to move the res.render inside the callback of the findOne function:

    col.findOne({"assignee" : "John Smith"}, function (err, doc) {

        assert.equal(null, err);

        // Print the resulting document to the console
        console.log("Here is my doc: %j", doc);

        res.render('index', doc);

        // Close the connection to the database
        db.close();

    }); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM