Mongoose Paginate
- 목록 조회 시 페이징을 위해 사용하는 라이브러리
설치
yarn add mongoose-paginate-v2
사용
Schema 파일
import * as mongoosePaginate from 'mongoose-paginate-v2';
export type SomeDocument = Some & Document;
@Schema()
export class Some {
}
const schema = SchemaFactory.createForClass(Some);
schema.plugin(mongoosePaginate);
export const SomeSchema = schema;
Injection 되는 곳 (ex: Service, Provider)
import { InjectModel } from '@nestjs/mongoose';
import { PaginateModel } from 'mongoose';
@Injectable()
export class SomeService {
constructor(
@InjectModel(Some.name)
private someModel: PaginateModel<SomeDocument>,
) {}
async getMessages(condition: string, page: number, limit: number) {
return this.someModel.paginate(
{ fieldName: condition },
{
sort: { createdAt: -1 },
limit,
page,
},
);
}
}
결과 값
{
"docs": [
{
"key" : "value",
"cratedAt": "2020-12-17T05:28:19.085Z",
"__v": 0
},
{
"key" : "value",
"cratedAt": "2020-12-17T05:28:18.142Z",
"__v": 0
},
{
"key" : "value",
"cratedAt": "2020-12-17T05:28:17.620Z",
"__v": 0
},
{
"key" : "value",
"cratedAt": "2020-12-17T05:27:33.305Z",
"__v": 0
}
],
"totalDocs": 4,
"limit": 10,
"totalPages": 1,
"page": 1,
"pagingCounter": 1,
"hasPrevPage": false,
"hasNextPage": false,
"prevPage": null,
"nextPage": null
}
참고