Skip to content

Instantly share code, notes, and snippets.

@lykmapipo
Last active August 29, 2015 14:20
Show Gist options
  • Save lykmapipo/a6536b50e8ee3411efd7 to your computer and use it in GitHub Desktop.
Save lykmapipo/a6536b50e8ee3411efd7 to your computer and use it in GitHub Desktop.
Mongoose Single Document Inheritance
'use strict';
//dependencies
var mongoose = require('mongoose');
var util = require('util');
var Schema = mongoose.Schema;
var async = require('async');
//Base Journal Entry Schema
function JournalEntry() {
Schema.apply(this, arguments);
//base jiurnal entry schema fields
this.add({
account: {
//full accounting model ref
type: String
},
journaledAt: {
type: Date,
default: new Date()
}
});
}
util.inherits(JournalEntry, Schema);
//Other accounting journal entry type extending JournalEntry
var Receipt = new JournalEntry({
customer: {
//full customer model ref
type: String
}
});
var Payment = new JournalEntry({
vendor: {
//full vendor model ref
type: String
}
});
//compile into models
var Journal = mongoose.model('Journal', new JournalEntry());
var Receipt = Journal.discriminator('Receipt', Receipt);
var Payment = Journal.discriminator('Payment', Payment);
async
.waterfall([
function connect(next) {
mongoose.connect('mongodb://localhost/sti', next);
},
function create(next) {
async
.parallel({
pay: function(after) {
Payment.create({
vendor: 'Jamin Inc',
account: 'Jamin Payable'
}, after);
},
receipt: function(after) {
Receipt.create({
customer: 'James Shop',
account: 'Sales Revenue'
}, after);
}
}, next);
},
function find(results, next) {
async
.parallel({
all: function(after) {
Journal.find().exec(after);
},
payments: function(after) {
Payment.find().exec(after);
},
receipts: function(after) {
Receipt.find().exec(after);
}
}, next);
}
], function finish(error, results) {
if (error) {
console.log(error);
} else {
console.log('\nAll Journal Entries:');
console.log(results.all);
console.log('\nPayments Journal Entries:');
console.log(results.payments);
console.log('\nReceipts Journal Entries:');
console.log(results.receipts);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment