1.1.0 • Published 4 years ago

mongoose-active-record v1.1.0

Weekly downloads
2
License
ISC
Repository
github
Last release
4 years ago

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!