Package Exports
- @casl/mongoose
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@casl/mongoose) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
CASL Mongoose
This package connects CASL and MongoDB. Basically 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
Installation
npm install @casl/mongoose @casl/ability
Getting Started
1. Integrating with mongoose
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 } = require('@casl/mongoose')
const mongoose = require('mongoose')
mongoose.plugin(accessibleRecordsPlugin)
Warning: make sure that you add that plugin before calling mongoose.model(...)
method. Models which were defined before adding plugin will not include accessibleBy
method.
Alternatively, you can selectively add plugin to any model:
// post.model.js
const mongoose = require('mongoose')
const { accessibleRecordsPlugin } = require('@casl/mongoose')
const Post = new mongoose.Schema({
title: String,
author: String
})
Post.plugin(accessibleRecordsPlugin)
module.exports = mongoose.model('Post', Post)
Afterwards you can fetch accessible records by doing this:
const Post = require('./post.model')
const ability = require('./ability') // defines Ability instance
Post.accessibleBy(ability).exec()
Check @casl/ability package to understand how to define abilities.
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 } = require('@casl/mongoose')
const { MongoClient } = require('mongodb')
const ability = require('./ability') // allows to update posts if author equals "me"
MongoClient.connect('mongodb://localhost:27017/blog', function(err, db) {
if (err) {
return console.error(err)
}
const query = toMongoQuery(ability, 'Post', 'update') // e.g., { $or: [{ author: 'me' }] }
if (query === null) {
// user is not allowed to update any posts
} else {
db.collection('posts').find(query) // find all Posts where author equals 'me'
}
db.close();
})
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