mongoose-active-record
v1.1.0
Published
Activerecord-like bindings for mongoose
Downloads
4
Maintainers
Readme
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:
- 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
Options
- 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
Contributing
Pull requests or issues welcome!