Skip to content

Commit

Permalink
fix(document): allow manually populating path within document array
Browse files Browse the repository at this point in the history
Fix #8273
  • Loading branch information
vkarpov15 committed Nov 3, 2019
1 parent b86749e commit dfde779
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 2 deletions.
14 changes: 14 additions & 0 deletions lib/document.js
Expand Up @@ -1167,6 +1167,20 @@ Document.prototype.$set = function $set(path, val, type, options) {
val = schema.applySetters(val, this, false, priorVal);
}

if (schema.$isMongooseDocumentArray &&
Array.isArray(val) &&
val.length > 0 &&
val[0].$__ != null &&
val[0].$__.populated != null) {
const populatedPaths = Object.keys(val[0].$__.populated);
for (const populatedPath of populatedPaths) {
this.populated(path + '.' + populatedPath,
val.map(v => v.populated(populatedPath)),
val[0].$__.populated[populatedPath].options);
}
didPopulate = true;
}

if (!didPopulate && this.$__.populated) {
delete this.$__.populated[path];
}
Expand Down
2 changes: 1 addition & 1 deletion lib/schematype.js
Expand Up @@ -1265,7 +1265,7 @@ SchemaType._isRef = function(self, value, doc, init) {
// - setting / pushing values after population
const path = doc.$__fullPath(self.path);
const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
ref = owner.populated(path);
ref = owner.populated(path) || doc.populated(self.path);
}

if (ref) {
Expand Down
2 changes: 1 addition & 1 deletion lib/types/documentarray.js
Expand Up @@ -86,7 +86,7 @@ class CoreDocumentArray extends CoreMongooseArray {
}
}
}

if (Constructor.$isMongooseDocumentArray) {
return Constructor.cast(value, this, undefined, undefined, index);
}
Expand Down
32 changes: 32 additions & 0 deletions test/model.discriminator.test.js
Expand Up @@ -1508,5 +1508,37 @@ describe('model', function() {
});
assert.strictEqual(doc.operations[0].pitchPath.path[0]._id, void 0);
});

it('with discriminators in embedded arrays (gh-8273)', function(done) {
const ProductSchema = new Schema({
title: String
});
const Product = mongoose.model('gh8273_Product', ProductSchema);
const ProductItemSchema = new Schema({
product: { type: Schema.Types.ObjectId, ref: 'gh8273_Product' }
});

const OrderItemSchema = new Schema({}, {discriminatorKey: '__t'});

const OrderSchema = new Schema({
items: [OrderItemSchema],
});

OrderSchema.path('items').discriminator('ProductItem', ProductItemSchema);
const Order = mongoose.model('Order', OrderSchema);

const product = new Product({title: 'Product title'});

const order = new Order({
items: [{
__t: 'ProductItem',
product: product
}]
});
assert.ok(order.items[0].product.title);
assert.equal(order.populated('items.product').length, 1);

done();
});
});
});

0 comments on commit dfde779

Please sign in to comment.