mddanielewicz mddanielewicz -5 years ago 236
Jade Question

Output mongoDB aggregation result with Jade

I'm trying to get a random object from my database to be displayed on the website. When I comment out the Jade portion listed below, nothing breaks. When I uncomment it I get:

TypeError: C:\Users\Malachi\Sandbox\CEC\myapp\views\layout.jade:63

61| .office-devide
62| h2 Patient Reviews
>> 63| each user in userreviews
64| ul
65| li= user.reviewfirstname
66| li= user.reviewlastname

Cannot read property 'length' of undefined

I'm not sure what I am doing wrong. I've looked around at a few other similar problems here and can't seem to figure out what I'm doing wrong. Any help would be appreciated. If you require additional information let me know. Thanks!

Express code

router.get('/', function(req, res, next) {
var db = req.db;
var collection = db.get('userreviews');
collection.aggregate( [ {sample: { size: 3} } ] ,function(e,docs){
res.render('index', {
title: 'Reviews',
"userreviews" : docs

Jade code

h2 Patient Reviews
each user in userreviews
li= user.reviewfirstname
li= user.reviewlastname
li= user.reviewsite
li= user.reviewdate
li= user.reviewtext

Answer Source

Try it with toArray like so

collection.aggregate([ {$sample: { size: 3} }]).toArray(function(e,docs) {
    res.render('index', {
      title: 'Reviews',
      userreviews : docs

In addition you have to use $sample, i.e. add a '$' to your stage operator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download