Skip to content

Instantly share code, notes, and snippets.

@jsanchezba
Created March 15, 2023 09:21
Show Gist options
  • Save jsanchezba/de6aba3b8b62946fb9c3ffc86e8f587e to your computer and use it in GitHub Desktop.
Save jsanchezba/de6aba3b8b62946fb9c3ffc86e8f587e to your computer and use it in GitHub Desktop.
Mongoose virtual properties with CASL
import fastify from './fastify'
import mongoose from 'mongoose'
import { accessibleRecordsPlugin, accessibleFieldsPlugin } from '@casl/mongoose'
mongoose.plugin(accessibleRecordsPlugin)
mongoose.plugin(accessibleFieldsPlugin, {
getFields: (schema: Record<string, unknown>) =>
Object.keys({
...(schema as { paths: object }).paths,
...(schema as { virtuals: object }).virtuals,
}),
})
import 'models/index'
const main = async () => {
try {
const connectionURL = process.env.MONGO_URL || ''
await mongoose.connect(connectionURL)
fastify.log.info('Connected to mongodb')
} catch (error) {
fastify.log.error('Failed to connect to mongo cluster: ' + error)
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment