Mongoose does not recognized "discriminated" subdoc's fields
Closed this issue · 1 comments
Is there an existing issue for this?
- I have searched the existing issues
Current behavior
I have a base RootDoc
with an embedded subDoc: SubDoc
.
The SubDoc
is "discriminated", with child classes FooSubDoc
and BarSubDoc
.
When querying on child subdoc's fields e.g. subDoc.fooId
, mongoose does not recognize the field, even when it exists on FooSubDoc
.
Therefore, if strict=true
the filter will be stripped off. If strict=throw
(my favorite), it will throw. strict=false
works, but I would rather not use it.
I found a trick on stackoverflow topics to have the creation work:
RootDocSchema.path('subDoc').discriminator(SubDocKind.Foo, FooSchema);
RootDocSchema.path('subDoc').discriminator(SubDocKind.Bar, BarSchema);
Doing so makes mongoose accept the subdoc fields during creation.
But it doesnt seem to make it accept the subdoc fields during querying.
In @nestjs/mongoose
it seems like the way to bind child classes to their base class is to use the discriminator
list in Mongoose.forFeature
. I tried it without success.
MongooseModule.forFeature([
{ name: RootDoc.name, schema: RootDocSchema },
{ name: ISubDoc.name, schema: ISubDocSchema, discriminators: [
{ value: SubDocKind.Foo, schema: FooSchema, name: FooSubDoc.name },
{ value: SubDocKind.Bar, schema: BarSchema, name: BarSubDoc.name },
] },
]),
Minimum reproduction code
https://github.com/OoDeLally/nestjs-mongoose-discriminator-strict-bug
Steps to reproduce
yarn
yarn start:debug
Expected behavior
The fields should be recognized as a possible path.
Package version
9.2.0
mongoose version
6.6.0
NestJS version
9.0.11
Node.js version
14.20.0
In which operating systems have you tested?
- macOS
- Windows
- Linux
Other
No response
Please, use our Discord channel (support) for such questions. We are using GitHub to track bugs, feature requests, and potential improvements.