Javascript/nodejs

[Node.js] mongoose 페이지네이션 구현(pagination)

뉴벡엔드 2024. 1. 2. 00:03

데이터를 한번에 가져오는게 아니라 나눠서 가져오는것(게시판이나 인스타 게시물)

 

 

 

 

모듈 설치

 

npm install mongoose-paginate-v2

 

 

 

 

model에 내용추가

 

const mongoosePaginate  = require('mongoose-paginate-v2')
exampleSchema.plugin(mongoosePaginate)

 

 

 

Controller에 내용추가 

const index = (req, res, next) => {
            Example.paginate({}, { page: req.query.page, limit: req.query.limit })
            .then(response => {
                res.json({
                    response
                })
            })
            .catch(error => {
                res.json({
                    message: "Error : " + error
                })
            })
}

 

 

?page=1&limit=10

같이 url query를 사용함(1 페이지, 10개까지 보여주기)

 

반응형