-1

I'm fairly new to node.js and MongoDB so bear with me. I have a form which stores details into a MongoDB collection; I then query this using .findOne (for now). I'm basically trying to pass this value into my index.ejs file and display it as part of the table. So the table should appear:

Name: Connor in the web browser.

My code for querying the database:

router.get('/', function(req, res) {
    res.render('admin/index');

    MongoClient.connect("mongodb://localhost:27017/tickets", function(err, db) {
        // Ensure we have connected
        if(err) {
            console.log("Cannot connect to database");
        } else {
            console.log("Connected to database");
        }
        // Create a collection to query
        var collection = db.collection('tickets');
        collection.findOne({name:String}, function(err, item) {
            // Ensure we have found the ticket
            if(err) {
                console.log("There was a problem finding the ticket.");
            } else {
                console.log("Ticket found!");
            }
        });
    });
});

My code generating the table:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Subject</th>
            <th>Message</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>
TRiG
  • 10,148
  • 7
  • 57
  • 107
Connor McFadden
  • 441
  • 1
  • 4
  • 20

1 Answers1

16

If you render the page after you've retrieved the document, then you can pass the document or some of its properties onto the template by doing something like the following. You can try it out by putting it in the callback to the findOne().

res.render('admin/index', { name: item['name'] });

Then you will be able to access it from your EJS template as follows:

<td>
    <%= name %>
</td>

If you want more information, you might want to have a look at this tutorial.

TLama
  • 75,147
  • 17
  • 214
  • 392
Juan Carlos Farah
  • 3,829
  • 30
  • 42