如何在车把上分页搜索结果

时间:2018-09-04 16:49:07

标签: javascript node.js mongodb express handlebars.js

当我搜索---产品正在显示..但是,当我单击第2页时,出现错误...我该如何在车把上分页搜索结果。

这是我的搜索路线。

router.get('/products-search',function(req,res,next){
    const perPage = 1;
    const page = req.query.page || 1;
    const title = "Ahl.com: "+ req.query['search'];
    Product.find({"tags" : {"$regex": req.query['search'], "$options": "i"}}).sort('-date').skip((perPage * page) - perPage).limit(perPage)
    .then(products => {
        Product.countDocuments({"tags" : {"$regex": req.query['search'], "$options": "i"}}).then(productCount=>{
            res.render("categories/search", {title:title , products:products , current: parseInt(page), pages:Math.ceil(productCount / perPage)});
        });
    })
    .catch(err => console.log("Search err"));

})

我用于分页的车把助手

paginate: function(options){
        let output = "";

        if(options.hash.current === 1){
            output += `<li class="page-item disabled"><a class="page-link">F</a></li>`;
        }else{
            output += `<li class="page-item"><a href="?page=1" class="page-link">F</a></li>`;
        }

        let i = (Number(options.hash.current) > 5 ? Number(options.hash.current) - 4 : 1);

        if(i !== 1){
            output += `<li class="page-item disabled"><a class="page-link">....</a></li>`;
        }

        for(; i <= (Number(options.hash.current) + 4) && i <= options.hash.pages; i++){
            if(i === options.hash.current){
                output += `<li class="page-item active"><a class="page-link">${i}</a></li>`;
            }else{
                output += `<li class="page-item"><a href="?page=${i}" class="page-link">${i}</a></li>`;
            }
            if(i === Number(options.hash.current) + 4 && i < options.hash.pages){
                output += `<li class="page-item disabled"><a class="page-link">....</a></li>`;
            }
        }

        if(options.hash.current === options.hash.pages){
            output += `<li class="page-item disabled"><a class="page-link">L</a></li>`;
        }else{
            output += `<li class="page-item"><a href="?page=${options.hash.pages}" class="page-link">L</a></li>`;
        }

        return output;
    }

分页链接

<div class="container">
  <nav aria-label="Page navigation example">
    <ul class="flex-wrap pagination">
        {{#paginate current=current pages=pages}}{{/paginate}}

    </ul>
  </nav>
</div>

1 个答案:

答案 0 :(得分:0)

这是我对任务进行分页,过滤和排序的方式,我发送了一个页面数组,其中包含每个元素的页码,限制和跳过:

router.get('/tasks', auth, async (req, res) => {
    const match = {};
    const sort = {};
    const limit = parseInt(req.query.limit);
    const skip = parseInt(req.query.skip);

    if (req.query.completed) {
        match.completed = req.query.completed === 'true';
    }

    if (req.query.sortBy) {
        const parts = req.query.sortBy.split(":");
        sort[parts[0]] = parts[1] === 'desc'? -1 : 1;
    }

    try {
        await req.user.populate('tasks').execPopulate({
            path: 'tasks',
            match,
            options: {
                sort,
                limit,
                skip
            }
        });
        
        const totalTasks = await Task.countDocuments({ owner: req.user._id }); 

        const pages = Array.from({ length: Math.ceil(totalTasks / limit) },(v, idx) => {
            return {
                num: idx + 1,
                limit,
                skip: (limit * (idx + 1)) - limit
            }
        });

        res.render('tasks', {
            tasks: req.user.tasks,
            enablePaging: totalTasks > limit,
            pages,
            limit
        });
    } catch (error) {
        res.status(500).send(error);
    }
});

在hbs模板中,我使用每个助手来遍历页面数组:

        {{#if enablePaging}}
        <div class="tasksPaging">
            Pages:
            {{#each pages}}
            <a href="/tasks?limit={{limit}}&skip={{skip}}">
                {{num}}
            </a>
            {{/each}}
        </div>
        {{/if}}

        <ul id="taskList">
            {{#each tasks}}
                <li>
                    <input type="checkbox" {{#if completed }} checked="checked" {{/if}} onclick="toggleTask('{{ _id }}', {{ completed }})">
                    <input type="text" value="{{ description }}" onchange="updateTask('{{ _id }}', this)">
                    <button onclick="deleteTask('{{ _id }}')" class="deleteBtn">
                        x
                    </button>
                </li>
            {{/each}}
        </ul>

这就是我访问/ tasks?limit = 4时的样子 Task manager