jonlil / mongoose-paginate

mongoose-paginate
MIT License
26 stars 1 forks source link

how to mongodb query operators to make custom conditions in paginate's query? #1

Closed yi closed 10 years ago

yi commented 10 years ago

Hi, I wish to use mongodb query operators alone with your paginate. But I can't find a proper way to mix them in.

Following is my code:

  TicketSchema.statics.list = function(status, after, callback) {
    var where;
    where = [];
    if (STATUS.isValid(status)) {
      where.push({
        status: status
      });
    }
    if (after != null) {
      where.push({
        after: after
      });
    }
    where = {
      $and: where
    };
    return this.paginate(where, '_id').execPagination(callback);
  };

and I got following error in execution:

  1) test models/ticket should able to list tickets:
     TypeError: Cannot read property 'after' of undefined
      at Function.schema.statics.paginate (/Users/imac/workspaces/node-ticket-system/node_modules/mongoose-paginator/lib/index.js:41:19)
      at Function.TicketSchema.statics.list (/Users/imac/workspaces/node-ticket-system/lib/models/ticket.js:180:17)
      at Context.<anonymous> (/Users/imac/workspaces/node-ticket-system/lib/tests/models_ticket_test.js:129:23)
jonlil commented 10 years ago

Hi @yi ,

Im happy to see you creating this first issue :) congratz.

The .paginate method takes an expressjs req object and uses the query object(parsed querystring) and this is where your code breaks

This should do the trick for your case

// just to clarify
var paginator = require('mongoose-paginator');
TicketSchema.plugins(paginator);

TicketSchema.statics.list = function(status, after, callback) {
  var where, q;
  where = [];
  q = { query: {}};
  if (STATUS.isValid(status)) {
    where.push({
      status: status
    });
  }

  if (after != null) {
    q.query.after = after;
  }
  where = {
    $and: where
  };
  return this.paginate(q, '_id').where(where).execPagination(callback);
};
yi commented 10 years ago

Hi Jonlil,

Thanks for your reply. That solves my problem.

And personally, I would suggest to decouple from express js. That I think it will be better for paginator to take the req.body as input parameter rather then the whole req.

Cheers

jonlil commented 10 years ago

Hi yi, thank you for tour input. I have consider this but waited with it. And your suggestion makes perfect sense so I will implement it asap.

jonlil commented 10 years ago

The paginator as it is at the moment uses req.query and not req.body, this is just to clarify

yi commented 10 years ago

NICE :+1: