0.1.1 • Published 7 years ago

mongoosefromclass v0.1.1

Weekly downloads
4
License
MIT
Repository
github
Last release
7 years ago

mongoosefromclass

© Ironboy 2017, MIT licensed

What does it do?

This module converts an ES6 class to a mongoose model.

How?

First require mongoose and this module

// Require
var mongoose = require('mongoose');
require('mongooseFromClass')(mongoose);

MongooseFromClass has now added a method to mongoose - mongoose.fromClass.

Then write a class definition

// The kitten class
class Kitten {
  
  schema(){
    // return the basic schema
    return {
      name: String
    };
  }

  alterSchema(schema){
    // optional method: do something
    // with the schema object
    // created by mongoose
  }

  // normal methods from here

  speak(){
    var greeting = this.name
    ? "Meow name is " + this.name
    : "I don't have a name";
    return greeting;
  }

}

Please note:

  • We do not have a constructor. Mongoose will provide one.
  • We must have a method named schema that returns a Mongoose schema.
  • We can add a method named alterSchema that changes the finished schema generated by Mongoose, just before it compiles to a model.

Last - convert the class into a Mongoose model

// Convert it to a mongoose model
Kitten = mongoose.fromClass(Kitten);

A note about inheritance

You can use inheritance - extends with your classes. But if you have already converted a class to a mongoose model then you must use the orgClass property when you extend:

// The Cat class has already been converted to a model
// so when we want use it to extend the Kitten class we
// must do the following

class Kitten extends Cat.orgClass {
  /* methods */
}