0

Imagine below sample datas:

TestDB

  {
    "_id": "56caf46a97bbe1b24163ef81",
    "age": 40,
    "eyeColor": "red"
  },
  {
    "_id": "56caf46a460b1d91a0d882d8",
    "age": 29,
    "eyeColor": "green"
  },
  {
    "_id": "56caf46afd859790720a2bb8",
    "age": 27,
    "eyeColor": "brown"
  },

I have to render:

  • TestDB.eyeColor (red, green, brown)
  • The number of TestDB documents (3)

to view page at the sametime.

I'm using express, so I should use res.render('view', {data}).

I tried like that :

app.get('/somePage', function(req, res, next){
    TestDB.find({}, function(err, dbs){
        res.render('view', {'eyeColor' : dbs.eyeColor })
    }).count(function(err, count){

       // How can I render this 'count' to view at the sametime?
       // If I render at here, I can't use above dbs.eyeColor, 
       // Same, If I render at above, I can't use count. 

       // Ok, There is a way to separate find() and count()
       // And make a variable and then render with this, 
       // Should I do like that? I think there must be easy way. 



    })
});
ton1
  • 7,238
  • 18
  • 71
  • 126
  • Also, as just stated `dbs` is an "array"! So `dbs.eyeColor` is invalid. Instead you want, `res.render('view', { "eyeColor": dbs.map(function(el) { return el.eyeColor }) })`. Or some variant thereof. – Blakes Seven Feb 22 '16 at 12:20

1 Answers1

0

If the eyeColor could be distinct, with distinct could be better as following. It will return the eysColor as one array ['red', 'green', 'brown'], then render it to view directly, the count could be retrieved through colors.length.

TestDB.distinct('eyeColor', function(error, colors) {
    res.render('view', {'eyeColor' : colors})
});

If the eyeColor could be duplicate values, then could be done as Blackes shown in the comments

TestDB.find({}, function(error, vals) {
    res.render('view', {'eyeColor' : vals.map(function(v) {return v.eyeColor;});})
});
zangw
  • 43,869
  • 19
  • 177
  • 214