Skip to content

Commit

Permalink
fix(populate): make getSchemaTypes() handle embedded discriminators w…
Browse files Browse the repository at this point in the history
…ithout a ref

Re: #5970
  • Loading branch information
vkarpov15 committed Jan 23, 2018
1 parent 51511af commit 5b78dba
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/services/populate/getSchemaTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ var Mixed = require('../../schema/mixed');
var mpath = require('mpath');

/*!
* ignore
* @param {Schema} schema
* @param {Object} doc POJO
* @param {string} path
*/

module.exports = function getSchemaTypes(schema, doc, path) {
Expand Down Expand Up @@ -73,14 +75,14 @@ module.exports = function getSchemaTypes(schema, doc, path) {
ret = [];
for (var i = 0; i < schemas.length; ++i) {
var _ret = search(parts.slice(p), schemas[i]);
if (_ret) {
if (_ret != null) {
_ret.$isUnderneathDocArray = _ret.$isUnderneathDocArray ||
!foundschema.schema.$isSingleNested;
if (_ret.$isUnderneathDocArray) {
ret.$isUnderneathDocArray = true;
}
ret.push(_ret);
}
ret.push(_ret);
}
return ret;
} else {
Expand Down
61 changes: 61 additions & 0 deletions test/helpers/populate.getSchemaTypes.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
'use strict';

var Schema = require('../../lib/schema');
var assert = require('assert');
var getSchemaTypes = require('../../lib/services/populate/getSchemaTypes');

describe('getSchemaTypes', function() {
it('handles embedded discriminators (gh-5970)', function(done) {
var ItemSchema = new Schema({
title: {
type: String,
required: true
}
}, {discriminatorKey: 'type'});

var ItemBookSchema = new Schema({
author: {
type: String,
ref: 'Ref1'
}
});

var ItemEBookSchema = new Schema({
author: {
type: String,
ref: 'Ref2'
}
});

var OtherItem = new Schema({ name: String });

var BundleSchema = new Schema({
items: [{
type: ItemSchema,
required: false
}]
});

BundleSchema.path('items').discriminator('Book', ItemBookSchema);
BundleSchema.path('items').discriminator('EBook', ItemEBookSchema);
BundleSchema.path('items').discriminator('Other', OtherItem);

var doc = {
items: [
{ type: 'Book', author: 'test 1' },
{ type: 'EBook', author: 'test 2' },
{ type: 'Other' },
]
}
var schemaTypes = getSchemaTypes(BundleSchema, doc, 'items.author');

assert.ok(Array.isArray(schemaTypes));
// Make sure we only got the schema paths for Book and EBook, and none
// for the 'Other'
assert.equal(schemaTypes.length, 2);
assert.equal(schemaTypes[0].options.ref, 'Ref1');
assert.equal(schemaTypes[1].options.ref, 'Ref2');

done();
});
});

0 comments on commit 5b78dba

Please sign in to comment.