【问题标题】:Mongoose limit and total count in mapReducemapReduce 中的 Mongoose 限制和总数
【发布时间】:2013-03-29 18:30:03
【问题描述】:

我需要运行一个查询,它返回文档的总数以及文档,并且可以限制和偏移。它类似于thisthis 问题。不同之处在于我运行 map/reduce 并且总数已经在 stats 参数中可用,所以希望我不必调用两次查询。

list: function (options, cb) {
    ...
    this.mapReduce(o, function (err, model, stats) {
        console.log('# of documents: %d ', stats.counts.output);
        model.find()
            .limit(criteria.perPage)
            .skip(criteria.perPage * criteria.page)
            .exec(cb);
    });
});

我像这样从控制器调用list 函数:

Track.list(options, function (err, docs) {
    res.json(docs);
});

是否可以将stats.counts.output 与返回的文档一起传递给控制器​​?

【问题讨论】:

  • 感谢您对stats.counts.output 的引用。我一直在寻找如何在单个查询中执行 .count().find() 并且至少在使用 mapReduce 时似乎是可能的。

标签: node.js mongodb mongoose


【解决方案1】:

您可以将cb 包装在exec 的参数中的函数中:

model.find()
    .limit(criteria.perPage)
    .skip(criteria.perPage * criteria.page)
    .exec(function (err, docs) {
      cb(err, docs, stats.counts.output)
    });

Track.list(options, function (err, docs, count) {
    res.json({docs: docs, count: count})
})

【讨论】:

    猜你喜欢
    • 2016-04-28
    • 2021-03-26
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    相关资源
    最近更新 更多