Search code examples
node.jsmongodbmongoosepaginationmongoose-schema

How to send paginated result as response after performing find operation in Mongodb?


I have this query to display in a table on frontend so I used paginate which is working fine

tableSchema.statics.getn = (query, options) => {
  return mongoose.model(MODEL_NAME).paginate(query, options);
};

But when I am trying to perform search query then I am unable to perform paginate on that. Is there any way to send response as paginated form to all the searched queries I tried following code

tableSchema.statics.search = query => {
  const Id = Number(query);
  const isNumeric = value => /^\d+$/.test(value);

  if (!isNumeric(query)) {
    if (query.includes("@")) {
      const regex = new RegExp(query, "i");
      return mongoose.model(MODEL_NAME).find({ "recipies.to": regex }).paginate(query);
    }
    return mongoose.model(MODEL_NAME).find({ "temp.name": query });
  }
  return mongoose.model(MODEL_NAME).find({ recipies: { Id } });
};

It is throwing me error that paginate is not a function. I tried storing find query result in object then performed paginate still it was not working.

I am using "mongoose-paginate-v2" for pagination


Solution

  • Hi I think you missed to add pagination pluging in model section.

    const mongoose = require('mongoose');
    const mongoosePaginate = require('mongoose-paginate-v2');
    
    const mySchema = new mongoose.Schema({
      /* your schema definition */
    });
    
    mySchema.plugin(mongoosePaginate);
    
    const myModel = mongoose.model('SampleModel', mySchema);
    
    myModel.paginate().then({}); // Usage
    

    You need to add mongoosePaginate in model as plugin.

    let options = {
        sort: { createdOn: 1 },
        page: 1,
        limit: 10
    };
    ModelName.paginate({ 'recipies.to': 'value' }, options, function (err, result) {
        if (err) {
            console.log(err);
        } else {
           // Here you will get paginate array please console and check
           console.log(result);
        }