Skip to content

Conversation

@vkarpov15
Copy link
Collaborator

Fix #12363
Fix #12440

Summary

The primary issue from #12363 and #12440 is that right now we call ref() functions on virtuals with the top-level document rather than the subdocument, even if the virtual is defined on the subdocument. For example, in Mongoose 8, with the following setup, ref() would see this as an instance of ParentSchema, not the b subdocument.

        const ASchema = new Schema({
          name: String
        });

        const BSchema = new Schema({
          referencedModel: String,
          aId: ObjectId
        });

        BSchema.virtual('a', {
          ref: function() {
            return this.referencedModel;
          },
          localField: 'aId',
          foreignField: '_id',
          justOne: true
        });

        const ParentSchema = new Schema({
          b: BSchema
        });

        const A1 = db.model('Test1', ASchema);
        const A2 = db.model('Test2', ASchema);
        const Parent = db.model('Parent', ParentSchema);

With this PR, we will call ref() with the subdocument. This is more consistent with how things work in conventional populate: ref() would get called with the subdoc in virtual populate, see #8469 and this test.

Examples

If you're using ref() as a function, it is easier to get the top-level document from the subdocument (using subdoc.ownerDocument()) than it is to get the correct subdocument from the top-level document. Plus, calling ref() with the subdocument helps make schemas easier to reuse.

@vkarpov15 vkarpov15 added this to the 9.0 milestone Jun 5, 2024
@vkarpov15 vkarpov15 requested a review from hasezoey June 5, 2024 19:56
Copy link
Collaborator

@hasezoey hasezoey left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, should a migrate entry be added in this PR itself, or later?

@vkarpov15
Copy link
Collaborator Author

Later, since we don't have a migrating_to_9 doc yet

@vkarpov15 vkarpov15 merged commit eb422c1 into 9.0 Jun 10, 2024
@hasezoey hasezoey deleted the vkarpov15/gh-12363 branch June 11, 2024 15:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants