
🐦 Monjoi
Monjoi - A lightweight alternative to Mongoose.
Features
- Natively written in TypeScript
- Schema's with Joi
- Pre and Post Hooks (a.k.a Plugins)
- Pagination // TODO
- Partial Schema Validation for Updates // TODO
- Automatic Timestamp insertion / updating // TODO
Install
npm i monjoi
yarn add monjoi
* Monjoi has peer dependencies on Joi and node mongodb driver.
Examples
Creating a collection.
- First declare the Schema and Type, then export the Data Access Object (DAO) and Type.
import Joi from 'joi'
import { collection } from 'monjoi'
export type Person = {
name: string
age?: number
}
const PersonSchema = Joi.object<Person>({
name: Joi.string().required(),
age: Joi.number()
})
export const PersonDAO = collection('person', PersonSchema)
- Dependency Inject your new DAO into any service to get access to the collection.
import { Person, PersonDAO } from './person.model.ts'
class PersonService {
constructor(
private personDAO: PersonDAO
) {}
public async createPerson(person: Person): Promise<Person> {
return this.personDAO.insertOne(person)
}
}
Hooks (Plugins)
There are 2 types of hooks available:
- Pre Hooks - Functions that execute before running the db access
- Post Hooks - Functions that execute after running the db access
Hooks can return regular values or even Promises.
Pre hooks
Useful for triggering other operations before accessing the db. If a hook returns a rejected promise, then the main db operation will not execute, neither will the Post hooks.
Post hooks
Useful for formatting db responses or triggering other operations. Post hooks should generally return objects because they will be passed to the next hook.
Any hook that returns a rejected promise will cancel the hook chain.
Hook Examples
Hooks are declared when defining your DAO. You can hook into any standard mongodb collection operation.
export const PersonDAO = collection('person', PersonSchema, {
insertOne: {
pre: [
() => console.log('I will run before any insertOne operation for person collection'),
() => console.log('me too!')
],
post: [
(insertedDoc) => {
console.log(`Document ${insertedDoc._id} created!`)
return insertedDoc
},
(insertedDoc) => {
return omit(insertedDoc, ['__v'])
}
]
}
})