【问题标题】:Mongoose - Customize skip and limit for the first timeMongoose - 首次自定义跳过和限制
【发布时间】:2018-04-06 09:18:31
【问题描述】:

我有点陷入困境。我真的想要一个简单的查询。我想计算来自查找查询的所有结果,然后我想应用跳过和限制,但不是第一次。简单来说,我首先想要所有项目及其数量。基于此,我想在结果上应用 skip 和 limit 。我怎么能做到这一点,我被卡住了。我尝试了不同的方法,例如将第一个查询结果存储在变量中并应用find() limit() skip(),但它不起作用。

样本 这是我到目前为止所做的。

Product.find({
        'category.category_name': request
    },
    function (err, searchedResults) {
        if (err) {
            return res.status(500).send("There was a problem getting the category based record .");

        } else {
            //Assign searched results length as product Count
            productCount = searchedResults.length;

            // apply ceiling - to make total pages
            totalPages = Math.ceil(productCount / pageOptions.limit);

            // tell the pagination what is the kind of pagination
            kindOfPagination = 'searchProduct';

            // call pagination func
            pagination(productCount, totalPages, pageOptions.page, pageOptions.limit, kindOfPagination);

            res.status(200).json({
                'products': searchedResults,
                '_meta': _meta
            });
        }
    })

现在我需要应用 skiplimit 部分。像这样

跳过和限制

 Product.find().skip(pageOptions.page * pageOptions.limit)
    .limit(parseInt(pageOptions.limit))
    .exec('find', function (err, products) {
        if (err) {
            res.status(500).json(err);
            return;
        } else {
            res.status(200).json({
                'products': products, // consuming the product variable
                '_meta': _meta
            });
        }
    });

现在在skiplimit 中,我希望应用从样本返回的结果。我怎样才能做到这一点 ?我以前试过这个。

我尝试过的

    Product.find({
            'category.category_name': request
        }).skip(req.query.page * 10)
        .limit(parseInt(10))
        .exec('find', function (err, searchedResults) {
            if (err) {
                return res.status(500).send("There was a problem getting the category based record .");

            } else {
                pageOptionsFunc(req.query.page);

                //Assign searched results length as product Count
                productCount = searchedResults.length;

                // apply ceiling - to make total pages
                totalPages = Math.ceil(productCount / pageOptions.limit);

                // tell the pagination what is the kind of pagination
                kindOfPagination = 'searchProduct';

                // call pagination func
                pagination(productCount, totalPages, pageOptions.page, pageOptions.limit, kindOfPagination);

// I am storing the results in a searchResultsSample
 searchResultsSample  = searchedResults;

                res.status(200).json({
                    'products': searchedResults,
                    '_meta': _meta
                });
            }
        })

查看搜索结果示例。现在我使用了skiplimit 部分。像这样

searchResultsSample.find().skip(pageOptions.page * pageOptions.limit)
    .limit(parseInt(pageOptions.limit))
    .exec('find', function (err, products) {
        if (err) {
            res.status(500).json(err);
            return;
        } else {
            res.status(200).json({
                'products': products, // consuming the product variable
                '_meta': _meta
            });
        }
    });

但它不起作用,我得到了一个未定义的错误函数。我怎样才能做到这一点 ?

【问题讨论】:

  • 不完全是一个新概念。 “跳过”总是n-1 乘以您所在页面的页面大小。因此页面1 变为.skip((1 - 1) * 25 )0 并且页面大小为25 页面2 变为skip((2 - 1) * 25) 或简单地25,等等。所以你总是想要代码中的“两者”。只是第一页的值1-1 变成了0
  • okaye @neil 但是限制老兄呢?我怎么能第一次忘记限制?
  • @neil 你能检查一下答案是否正确?
  • 你总是限制。在“分页”中没有可能的情况是您不要求限制,否则很简单。这是一个永远不会改变的古老过程。

标签: node.js mongodb api mongoose


【解决方案1】:

先计数,然后应用跳过和限制。

router.get('/products', function (req, res) {

    let items_perpage = req.query.itemsperpage || 5;
    let page = req.query.page || 1;

    let skip = items_perpage * (page - 1);
    let limit = parseInt(items_perpage);

    Product.find({'category.category_name': request}).count(function (err, totalCount) {
        if (err) {
            logger.error(err.stack);
            return res.status(500).send({ success: false, msg: 'Internal Server Error' })
        }
        else {
            Product.find({
                'category.category_name': request
            }).skip(skip).limit(limit).exec(function (err, searchedResults) {
                if (err) {
                    logger.error(err.stack);
                    return res.status(500).send({ success: false, msg: 'Internal Server Error' })
                }
                else {
                    let total = {}
                    total.count = totalCount;
                    if (total.count % items_perpage == 0) {
                        total.pages = (total.count / items_perpage);
                    }
                    else {
                        total.pages = (parseInt(total.count / items_perpage) + 1);
                    }
                    return res.status(200).send({ success: true, msg: 'All Products', total: total, data: searchedResults });
                }
            });
        }
    })
});

【讨论】:

  • else中的第二个find,是否应用于结果?
  • 是的,首先我根据您的搜索数据计算产品,其次,我对数据应用跳过和限制并返回结果。
  • 让我试试吧兄弟。
猜你喜欢
  • 2010-11-27
  • 1970-01-01
  • 2015-03-12
  • 2016-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
相关资源
最近更新 更多