【问题标题】:Mongoose find() and count() at the sametime [duplicate]猫鼬find()和count()同时[重复]
【发布时间】:2016-06-03 20:34:24
【问题描述】:

想象下面的示例数据:

测试数据库

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

我必须渲染:

  • TestDB.eyeColor(红色、绿色、棕色)
  • TestDB 文档数 (3)

同时查看页面。

我使用的是 express,所以我应该使用 res.render('view', {data})。

我试过这样:

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. 



    })
});

【问题讨论】:

  • 另外,正如刚才所说,dbs 是一个“数组”!所以dbs.eyeColor 无效。相反,您想要res.render('view', { "eyeColor": dbs.map(function(el) { return el.eyeColor }) })。或者它的一些变体。

标签: node.js mongodb mongoose


【解决方案1】:

如果eyeColor 可以不同,distinct 可能会更好,如下所示。它将eysColor作为一个数组['red', 'green', 'brown']返回,然后直接渲染查看,count可以通过colors.length检索。

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

如果eyeColor 可能是重复值,则可以按照 cmets 中显示的 Blackes 来完成

TestDB.find({}, function(error, vals) {
    res.render('view', {'eyeColor' : vals.map(function(v) {return v.eyeColor;});})
});

【讨论】:

    猜你喜欢
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2014-05-30
    • 1970-01-01
    • 2020-04-11
    相关资源
    最近更新 更多