Error: Mongoose array discriminator not applied to array elements
0 reputation · 15 Sept 2020, 01:39 UTC
Goal
Preserve subtype information for subdocuments stored inside an array field of a parent schema, so that each element retains its specific discriminator type after a document is saved and later retrieved.
Constraints & Uncertainty
Mongoose 6+ and 7.x support discriminators for single nested subdocuments via Schema.discriminator(), but the framework does not propagate the discriminatorKey to elements of an array field. When a discriminated subdocument instance is pushed into the array, the key is omitted and the element is treated as the base type upon retrieval. This behavior is documented in the Mongoose Discriminators guide and is not slated for change in current releases.
Unresolved Questions
- What pattern can reliably attach the
discriminatorKeyto each array element without breaking schema validation? - Should a manual
Mixedtype or a custom pre/post middleware be used to enforce the key, and how does that affect query performance? - If future Mongoose releases add array discriminator support, what migration steps are required to update existing collections that currently lack the key?