Skip to content

Instantly share code, notes, and snippets.

@harrytwright
Last active November 21, 2019 17:38
Show Gist options
  • Save harrytwright/547e49d20423fff91327ffafe03a455b to your computer and use it in GitHub Desktop.
Save harrytwright/547e49d20423fff91327ffafe03a455b to your computer and use it in GitHub Desktop.
This is how to use discrimination and virtual prototypes, for future reference
'use strict';
var chai = require('chai')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const BaseSchema = new Schema({
name: { type: String, required: true }
}, { collection: 'products', discriminatorKey: 'type' });
BaseSchema.virtual('children', {
ref: () => { return 'Product'; },
localField: '_id',
foreignField: 'parent',
justOne: false
});
const ParentSchema = new Schema({
description: { type: String, required: true },
code: { type: String, required: false }
}, { discriminatorKey: 'type' });
const ChildSchema = new Schema({
parent: { type: mongoose.Types.ObjectId, ref: 'Product', required: true },
customer: { type: String, required: true }
}, { discriminatorKey: 'type' });
const Product = mongoose.model('Product', BaseSchema)
const Parent = Product.discriminator('Parent', ParentSchema)
const Child = Product.discriminator('Child', ChildSchema)
const { connection } = mongoose;
const expect = chai.expect;
const GH = 'models-discriminator-populate';
const URI = `mongodb://localhost:27017/${GH}`;
const OPTS = { family: 4, useNewUrlParser: true, useUnifiedTopology: true };
describe('models.discriminator.populate', function() {
var parent, child;
before('initialisation', async function() {
await mongoose.connect(URI, OPTS);
await connection.dropDatabase();
parent = new Parent({
name: 'Pumaseal P2 Clear',
description: 'Transparent almost clear polyurethane floor sealer / dust sealer for concrete. Single Pack',
code: 'P19U'
});
child = new Child({
name: 'Resiseal Clear',
customer: 'Resifloor',
parent: parent._id
});
await parent.save()
await child.save()
});
after('termination', async function() {
await connection.close();
});
describe('populate from product', function() {
it('should return aliases', async function() {
let productFound = await Product.findById(parent._id).populate('children');
expect(productFound.children[0].parent.toString(), 'Product.children[].product').to.equal(parent._id.toString());
});
});
describe('populate from parent', function() {
it('should return aliases', async function() {
let productFound = await Parent.findById(parent._id).populate('children');
expect(productFound.children[0].parent.toString(), 'Product.children[].product').to.equal(parent._id.toString());
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment