Search code examples
node.jsmongoosepaginationcasl

Using @casl/mongoose & mongoose-paginate-v2 together


I am trying to use @casl/mongoose with mongoose-paginate-v2 in my express.js app, but the problem is that both libs must be used on the model object.

  // trying this
  const results = await Person
      .accessibleBy(req['ability'])
      .paginate({}, options);

  // or this, the same problem
  const results = await Person
      .paginate({}, options)
      .accessibleBy(req['ability']);

In both ways, I got either accessibleBy/paginate is not a function because as I said both libs must be used on the model (in my case Person) object.

Any help or suggestion is highly appreciated.


Solution

  • @casl/mongoose supports statics and query methods of mongoose. so, you can do this:

    Person.findOne({ _id: id }).accessibleBy(ability).where({ createdAt: { $lt: new Date() } })
    
    // or
    Person.accessibleBy(ability).findOne({ _id: id }).where({ createdAt: { $lt: new Date() } })
    

    At the same time pagination plugin supports only static method because it sends multiple queries to db, so it's (probably) impossible to achieve what you want. Either talk to the author of that package and ask him to do smth with that or just write own pagination plugin