Reputation: 9417
I want to display all entries in my collection (mongodb) as html.
I've done this before with basic things, for example...
router.get('/', function (req, res) {
res.render('home', { title: 'Express', username: req.session.user, successful: req.query.valid });
});
Where I give username
and successful
values to be used as html, so that in my jade file I can display them like this...
body
p #{successful}
h1
|Welcome,
span #{username}
But now I want to loop through all entries in a particular collection in mongodb and display them through my jade file. How can I do this?
Upvotes: 0
Views: 935
Reputation: 308
You can use an iterator inside your view template to render all the elements inside the collection. In order to get all the element of that collection you need to define inside a router a query ( take a look at mongoose ). So, you can modify your code this way:
var Model = require('models/Model'); // this is your model schema
router.get('/', function (req, res) {
Model.find({}, function(err, result){
if(err)
return res.status(400).send(err);
// here were are passing to our view all the elements we got from out query
res.render('home', { title: 'Express', username: req.session.user, successful: req.query.valid, data: result });
});
});
Now we can define the iterator inside the jade template:
body
p #{successful}
h1
|Welcome,
span #{username}
ul
for element in data
li = element
Here I'm assuming you are using jade as template engine, mongodb as database and mongoose.
Upvotes: 2