A wrapper library to provide an elegant activerecord-like approach to creating mongoose models.
Traditional mongoose model
constanimalSchema=newSchema({name: String,type: String});// Creating an instance methodanimalSchema.methods.findSimilarTypes=function(){returnthis.model('Animal').find({type: this.type});};// Creating a static methodanimalSchema.statics.findByType=function(type){returnthis.find({ type });};constAnimal=mongoose.model('Animal',schema);constdog=newAnimal({type: 'dog'});constdogs=awaitdog.findSimilarTypes()constotherDogs=awaitAnimal.findByType('dog');Mongoose ActiveRecord model
classAnimal{//Schema definition staticgetname(){returnString}staticgettype(){return{type: String,index: true}}//Create a static methodstaticfindByType(type){returnthis.find({ type })}//Create an instance methodfindSimilarTypes(){returnthis.model('Animal').find({type: this.type});}}const{ Animal }=awaitmongooseActiveRecord(options)constdog=newAnimal({type: 'dog'});constdogs=awaitdog.findSimilarTypes()constotherDogs=awaitAnimal.findByType('dog');constmongooseActiveRecord=require('mongoose-active-record')constoptions={modelPath: path.join(__dirname,'./models'),connectionUrl: 'mongodb://localhost/test',connectionOptions: {useNewUrlParser: true},schemaOptions: {timestamps: true}}constmodels=awaitmongooseActiveRecord(options)const{ Pet }=modelsawaitPet.find({})// ./models/Pet.jsclassPet{staticgetsomeField(){returnString}staticstaticMethod(){console.log('do something')}instanceMethod(){console.log('do something else')}}module.exports=PetSpecifics:
- Static getters are converted into the schema. The getter can return any schema type
- Static methods are converted into static schema methods
- Standard class methods are converted into schema instance methods
- The models returned from mongooseActiveRecord are just mongoose models
- modelPath: Path to the directory where your models are defined.
- connectionUrl: Any valid mongoose connection string
- connectionOptions: Any valid mongoose connection option
- schemaOptions: any valid mongoose schema option
Pull requests or issues welcome!