使用Mongoose和Node.js进行分页的最佳方法

时间:2017-07-14 16:42:53

标签: javascript node.js mongodb mongoose pagination

我目前正在学习猫鼬,而且我一直在制作一个分页系统。我制作了两个代码,但我想知道哪一个是最好的方式来做我想要的性能和一切

脚本1:

app.get("/:page",(req,res)=>{
            post.find({}).then((data)=>{
                let per_page = 2; // set how many posts per page
                let num_page = Number(req.params.page);
                let max_pages = Math.ceil(data.length/per_page);
                if(num_page == 0 || num_page > max_pages){
                    res.render('404');
                }else{
                    let starting = per_page*(num_page-1)
                    let ending = per_page+starting
                    res.render('posts', {posts:data.slice(starting,ending), pages: max_pages, current_page: num_page});
                }
            });
    });

脚本2:

app.get("/:page",(req,res)=>{
        post.count({}, (err, len)=>{
            let per_page = 2;  // set how many posts per page
            let num_page = Number(req.params.page);
            let max_pages = Math.ceil(len/per_page);
            if(num_page == 0 || num_page > max_pages){
                res.render('404');
            }else{
                let starting = per_page*(num_page-1);
                let ending = per_page+starting;
                let promise = post.find({}).limit(per_page).skip(starting);
                promise.then((data)=>{
                    res.render('posts', {posts:data, pages: max_pages, current_page: num_page});
                });
            }
        });
    });

0 个答案:

没有答案