mongoose-schema-extend
Implements schema inheritance and an optional discriminator key which is useful for storing different types of related documents in a collection and fetching them with the correct model type.
Notice
From version 0.2.1 mongoose-schema-extend is using harmony proxies. You will need to add the flag --harmony_proxies to your start command if you're using it, or use a previous version.
Usage
Install via NPM
$ npm install mongoose-schema-extend
Schema Inheritance
You just require the library to add schema extend method
var mongoose = extend = ;var Schema = mongooseSchema; var PersonSchema = name : String collection : 'users' ; var EmployeeSchema = PersonSchema; var Person = mongoose Employee = mongoose; var Brian = name : 'Brian Kirchoff' department : 'Engineering'; ...
Discriminator Key
By adding the discriminatorKey schema option, a key is added to your saved documents with the model name and is used when finding documents of different types to set them to the correct model
...var VehicleSchema = mongoose; var CarSchema = VehicleSchema;var BusSchema = VehicleSchema var Vehicle = mongoose Car = mongoose Bus = mongoose; var accord = make : 'Honda' year : 1999;var muni = make : 'Neoplan' route : 33; accord
At this point in MongoDB you will have documents similar to this
{ "_type" : "car", "make" : "Honda", "year" : 1999, "_id" : ObjectId("5024460368368a3007000002"), "__v" : 0 }
{ "_type" : "bus", "make" : "Neoplan", "route" : 33, "_id" : ObjectId("5024460368368a3007000003"), "__v" : 0 }
When querying, the objects model prototype will be set based on the _type field, so they are fully functional
Vehicle;
Tests
To run the tests install mocha
npm install mocha -g
and then run
mocha