@casl/mongoose2.3.1 • Public • Published
This package connects CASL and MongoDB. In other words, it allows to fetch records based on CASL rules from MongoDB. That means you can easily answer on the question: "Which records can be read?" or "Which records can be updated?". Lets see how
npm install @casl/mongoose @casl/ability
1. Integrating with mongoose
There are 2 plugins which allow to seamlessly integrate CASL into mongoose:
Accessible Records plugin
accessibleRecordsPlugin is a mongoose plugin which adds
accessibleBy method to query and static methods. For example, you can add this plugin globally to all models
const accessibleRecordsPlugin =const mongoose =mongoose
Warning: make sure that you add that plugin before calling
mongoose.model(...) method. Models which were defined before adding plugin will not include
Alternatively, you can selectively add plugin to any model:
// post.model.jsconst mongoose =const accessibleRecordsPlugin =const Post =title: Stringauthor: StringPostmoduleexports = mongoose
Afterwards you can fetch accessible records by doing this:
const Post =const ability = // defines Ability instancePost
Check @casl/ability package to understand how to define abilities.
Permitted Fields plugin
permittedFieldsPlugin is a mongoose plugin which adds
permittedFieldsBy method to instance and static methods.
That method allow to retrieve accessible fields by ability:
const permittedFieldsPlugin =const mongoose =const PostSchema =const ability = // defines Ability instancePostSchemaconst Post = mongooseconst readableFields = Post // by default, returns fields for `read` action
Later, you can use that array of fields to return user only fields which he can read or pick ones from body which he can update!
const pick =app // express instance for example
The same method exists on Model instance and takes into consideration rule conditions & object properties as well. For example, if you have the next rules:
const ability = AbilityBuilderconst post = private: true title: 'Private post'Post // ['title', 'description']post // ['title']
Without knowing context (i.e.,
Post instance attributes)
permittedFieldsBy can't return the correct permitted fields. That's why it's recommended to use instance method instead of class method!
2. Integrating with any MongoDB library
In case you don't use mongoose, this package provides
toMongoQuery function which can convert CASL rules into MongoDB query. Lets see an example of how to fetch accessible records using raw MongoDB adapter
const toMongoQuery =const MongoClient =const ability = // allows to update posts if author equals "me"MongoClient
See Database integration for details
Want to help?
Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for contributing /d