aravindnc / mongoose-aggregate-paginate-v2

A cursor based custom aggregate pagination library for Mongoose with customizable labels.
MIT License
131 stars 23 forks source link
aggregate callback cursor custom label mongodb mongoose mongoose-aggregate mongoose-paginate next paginate pagination paginator paging plugin prev promise total

Banner

mongoose-aggregate-paginate-v2

npm version Build Status contributions welcome Downloads GitHub commit activity npms.io npms.io

A page based custom aggregate pagination library for Mongoose with customizable labels.

If you are looking for basic query pagination library without aggregate, use this one mongoose-paginate-v2

Installation

npm install mongoose-aggregate-paginate-v2

Usage

Adding the plugin to a schema,

var mongoose = require("mongoose");
var aggregatePaginate = require("mongoose-aggregate-paginate-v2");

var mySchema = new mongoose.Schema({
  /* your schema definition */
});

mySchema.plugin(aggregatePaginate);

var myModel = mongoose.model("SampleModel", mySchema);

and then use model aggregatePaginate method,

// as Promise

var myModel = require("/models/samplemodel");

const options = {
  page: 1,
  limit: 10,
};

var myAggregate = myModel.aggregate();
myModel
  .aggregatePaginate(myAggregate, options)
  .then(function (results) {
    console.log(results);
  })
  .catch(function (err) {
    console.log(err);
  });
// as Callback

var myModel = require('/models/samplemodel');

const options = {
    page: 1,
    limit: 10
};

var myAggregate = myModel.aggregate();
myModel.aggregatePaginate(myAggregate, options, function(err, results) {
    if(err) {
        console.err(err);
    else {
        console.log(results);
    }
})
// Execute pagination from aggregate
const myModel = require('/models/samplemodel');

const options = {
    page: 1,
    limit: 10
};

const myAggregate = myModel.aggregate();
myAggregate.paginateExec(options, function(err, results) {
    if(err) {
        console.err(err);
    else {
        console.log(results);
    }
})

Model.aggregatePaginate([aggregateQuery], [options], [callback])

Returns promise

Parameters

Return value

Promise fulfilled with object having properties:

Please note that the above properties can be renamed by setting customLabels attribute.

Sample Usage

Return first 10 documents from 100

const options = {
  page: 1,
  limit: 10,
};

// Define your aggregate.
var aggregate = Model.aggregate();

Model.aggregatePaginate(aggregate, options)
  .then(function (result) {
    // result.docs
    // result.totalDocs = 100
    // result.limit = 10
    // result.page = 1
    // result.totalPages = 10
    // result.hasNextPage = true
    // result.nextPage = 2
    // result.hasPrevPage = false
    // result.prevPage = null
  })
  .catch(function (err) {
    console.log(err);
  });

With custom return labels

Now developers can specify the return field names if they want. Below are the list of attributes whose name can be changed.

You should pass the names of the properties you wish to changes using customLabels object in options. Labels are optional, you can pass the labels of what ever keys are you changing, others will use the default labels.

If you want to return paginate properties as a separate object then define customLabels.meta.

Same query with custom labels


const myCustomLabels = {
  totalDocs: 'itemCount',
  docs: 'itemsList',
  limit: 'perPage',
  page: 'currentPage',
  nextPage: 'next',
  prevPage: 'prev',
  totalPages: 'pageCount',
  hasPrevPage: 'hasPrev',
  hasNextPage: 'hasNext',
  pagingCounter: 'pageCounter',
  meta: 'paginator'
};

const options = {
    page: 1,
    limit: 10,
    customLabels: myCustomLabels
};

// Define your aggregate.
var aggregate = Model.aggregate();

Model.aggregatePaginate(aggregate, options, function(err, result) {
if(!err) {
  // result.itemsList [here docs become itemsList]
  // result.itemCount = 100 [here totalDocs becomes itemCount]
  // result.perPage = 10 [here limit becomes perPage]
  // result.currentPage = 1 [here page becomes currentPage]
  // result.pageCount = 10 [here totalPages becomes pageCount]
  // result.next = 2 [here nextPage becomes next]
  // result.prev = null [here prevPage becomes prev]

  // result.hasNextPage = true [not changeable]
  // result.hasPrevPage = false [not changeable]
} else {
  console.log(err);
};

Using offset and limit

Model.aggregatePaginate(
  aggregate,
  { offset: 30, limit: 10 },
  function (err, result) {
    // result
  }
);

Using countQuery

// Define your aggregate query.
var aggregate = Model.aggregate();

// Define the count aggregate query. Can be different from `aggregate`
var countAggregate = Model.aggregate();

// Set the count aggregate query
const options = {
  countQuery: countAggregate,
};

Model.aggregatePaginate(aggregate, options)
  .then(function (result) {
    // result
  })
  .catch(function (err) {
    console.log(err);
  });

Using prepagination

This allows you to paginate the result at a given placeholder stage in a pipeline rather than at the end which is the default behavior. This can be useful when you have a large dataset and you want to paginate before carrying out expensive operations such as $lookup or $unwind.

// Define your pipeline
const pipeline = [
  {
    $match: {
      status: "active",
    },
  },
  {
    $sort: {
      date: -1,
    },
  },
  "__PREPAGINATE__",
  {
    $lookup: {
      from: "authors",
      localField: "author",
      foreignField: "_id",
      as: "author",
    },
  },
];
Model.aggregatePaginate(pipeline, options)
  .then(function (result) {
    // result
  })
  .catch(function (err) {
    console.log(err);
  });

Global Options

If you want to set the pagination options globally across the model. Then you can do like below,

let mongooseAggregatePaginate = require("mongoose-aggregate-paginate-v2");

let BookSchema = new mongoose.Schema({
  title: String,
  date: Date,
  author: {
    type: mongoose.Schema.ObjectId,
    ref: "Author",
  },
});

BookSchema.plugin(mongooseAggregatePaginate);

let Book = mongoose.model("Book", BookSchema);

// Like this.
Book.aggregatePaginate.options = {
  limit: 20,
};

Release Note

Moved to CHANGELOG.md

License

MIT