如何使用mongoose distinct,skip和limit [英] How use mongoose distinct, skip and limit together

查看:1313
本文介绍了如何使用mongoose distinct,skip和limit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用跳过限制进行分页, distinct 表示不返回相等的值。

I need to use skip and limit for pagination, and the distinct for not return equal values.

如果我使用

MyModel.find().distinct('blaster', function(err, results) {
    res.render('index', {
        data: results
    });
});

这样做。

如果我使用

MyModel.find().sort('brand').skip((page-1)*15).limit(15).exec(function(err, results) {
    res.render('index', {
        data: results
    });
});

这也有效,但如何同时使用?

This is also working, but how use both?

如果我尝试,错误将显示:

If i try, the error will show:

Error: skip cannot be used with distinct


推荐答案

你不这样做。 .distinct() 是一个返回数组的方法,因此你不能用光标修饰符修改不是光标的东西,比如 .limit() .skip()

你想要的是 .aggregate() 方法。不仅仅是添加东西:

What you want is the .aggregate() method. Much more than just adding things up:

MyModel.aggregate(
    [
        { "$group": { "_id": "$blaster" } },
        { "$skip": ( page-1 ) * 15 },
        { "$limit": 15 }
    ],
    function(err,results) {
       // results skipped and limited in here
    }
);

聚合框架提供了另一种实现不同结果的方法。但是以更灵活的方式。请参阅 $ group $ skip $ limit

The aggregation framework provides another way to achieve "distinct" results. But in a more flexible way. See the operators for $group, $skip and $limit.

这篇关于如何使用mongoose distinct,skip和limit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆