Skip to content

Model.hydrate() should work with subdocument array projection #14680

Closed
@lcrosetto

Description

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.4.3

Node.js version

20.14.0

MongoDB server version

7.0.11

Typescript version (if applicable)

No response

Description

When calling Model.hydrate() with a schema that includes a subdocument array, and passing a projection as the second argument, this projection does not get applied correctly to the subdocuments. The result is an array of empty objects in the subdocument array field.

I believe this might be related to the behavior of applyInclusiveProjection(), which is recursive and will call itself with the subdocument array as the first argument.

Steps to Reproduce

The following snippet will reproduce this behavior:

      const embedSchema = new mongoose.Schema({
        field1: String,
      });
      const testSchema = new mongoose.Schema({
        testField: {
          type: String,
          required: true,
        },
        testArray: [embedSchema],
      });
      const TestModel = mongoose.model('Test', testSchema);
      const obj = {
        _id: new mongoose.Types.ObjectId(),
        testField: 'foo',
        testArray: [{_id: new mongoose.Types.ObjectId(), field1: 'bar'}],
      };
      const res = TestModel.hydrate(obj, {'testArray.field1': true});

The result is an object that looks like:

{ testArray: [ {} ] }

The first level projection is applied correctly, but all keys in the subdocument have been deleted.

Expected Behavior

If a schema with an array of subdocuments is passed, the projection should be applied as expected, or throw an error if unsupported.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions