Skip to content

tswayne/mongoose-active-record

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

npm

Mongoose Activerecord

A wrapper library to provide an elegant activerecord-like approach to creating mongoose models.

Traditional mongoose model

const animalSchema = new Schema({ name: String, type: String });
// Creating an instance method
animalSchema.methods.findSimilarTypes = function() {
  return this.model('Animal').find({ type: this.type });
};

// Creating a static method
animalSchema.statics.findByType = function(type) {
  return this.find({ type });
};
const Animal = mongoose.model('Animal', schema);

const dog = new Animal({ type: 'dog' });
const dogs = await dog.findSimilarTypes()
const otherDogs = await Animal.findByType('dog');

Mongoose ActiveRecord model

class Animal {
  //Schema definition 
  static get name() { return String }
  static get type() { return { type: String, index: true } }

  //Create a static method
  static findByType(type) {
    return this.find({ type })
  }

  //Create an instance method
  findSimilarTypes() {
    return this.model('Animal').find({ type: this.type });
  }
}

const { Animal } = await mongooseActiveRecord(options)

const dog = new Animal({ type: 'dog' });
const dogs = await dog.findSimilarTypes()
const otherDogs = await Animal.findByType('dog');

Usage

const mongooseActiveRecord = require('mongoose-active-record')

const options = {
  modelPath: path.join(__dirname, './models'),
  connectionUrl: 'mongodb://localhost/test',
  connectionOptions: {
    useNewUrlParser: true
  },
  schemaOptions: {
    timestamps: true
  }
}

const models = await mongooseActiveRecord(options)
const { Pet } = models
await Pet.find({})

Model definition

// ./models/Pet.js
class Pet{
  static get someField() { return String }
  static staticMethod() {
   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

Watchers

Forks

Releases

No releases published

Packages

No packages published