Model.hydrate() should work with subdocument array projection #14680
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