Skip to content

Instantly share code, notes, and snippets.

@mallond
Created April 19, 2017 20:06
Show Gist options
  • Save mallond/f380eeefabbfd89eaa345e1f66b4017f to your computer and use it in GitHub Desktop.
Save mallond/f380eeefabbfd89eaa345e1f66b4017f to your computer and use it in GitHub Desktop.
Polymorphic Mongoose Example - discriminator - Easy to understand
const mocha = require('mocha');
const assert = require('assert');
const async = require('async');
describe('Test Mongo Connection and Detail Creation', () => {
it('should return result', (done) => {
"use strict";
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/temp');
const ProductInfo_0 = new Schema({
product: {
type: 'String'
},
multiVehicle: {
type: Boolean
},
singleVehiclePrice: {
type: Number
},
multipleVehiclePrice: {
type: Number
},
singleVehicleCommission: {
type: Number
},
multipleVehicleCommission: {
type: Number
},
insuredVehicles: []
});
const ProductInfo_1 = new Schema({
productCode: {
type: 'String'
},
multiVehicle: {
type: Boolean
},
singleVehiclePrice: {
type: Number
},
multipleVehiclePrice: {
type: Number
},
singleVehicleCommission: {
type: Number
},
multipleVehicleCommission: {
type: Number
},
insuredVehicles: []
});
var options = {
discriminatorKey: 'kind'
};
// Step 1 - Base Schema
var eventSchema = new mongoose.Schema({
time: Date
}, options);
var Event = mongoose.model('Event', eventSchema);
// Step 2 - add discriminator
var ClickedLinkEvent = Event.discriminator('ProductInfo_0',
new mongoose.Schema({
productInfo: ProductInfo_0
}, options));
// Step 2 - add discriminator
var ClickedLinkEvent2 = Event.discriminator('ProductInfo_1',
new mongoose.Schema({
productInfo: ProductInfo_1
}, options));
var event1 = new ClickedLinkEvent({
time: Date.now(),
productInfo: {
product: 'tada'
}
});
var event2 = new ClickedLinkEvent2({
time: Date.now(),
productInfo: {
productCode: 'tada'
}
})
var save = function(doc, callback) {
doc.save(function(error, doc) {
callback(error, doc);
});
};
async.map([event1, event2], save, function(error) {
done();
Event.count({}, function(error, count) {
assert.equal(count, 2);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment