Skip to content

Latest commit

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

npm

Mongoose Activerecord

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');

Usage

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({})

Model definition

// ./models/Pet.jsclassPet{staticgetsomeField(){returnString}staticstaticMethod(){console.log('do something')}instanceMethod(){console.log('do something else')}}module.exports=Pet

Specifics:

Options

Contributing

Pull requests or issues welcome!

About

Activerecord-like bindings for mongoose

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages