Do you want to request a feature or report a bug?
bug
What is the current behavior?
We have a schema with “Recursive embedded discriminators in arrays” (implemented following these instructions).
When parsing a given, nested object structure, Mongoose 5.10.3+ (up until 5.10.18) loses parts of the object tree. Mongoose 5.10.2 and below work fine.
If the current behavior is a bug, please provide the steps to reproduce.
import mongoose from 'mongoose';
beforeAll(async () => mongoose.connect(process.env.MONGO_URL as string));
afterAll(async () => mongoose.disconnect());
it('nested schema', () => {
const contentSchema = new mongoose.Schema({}, { discriminatorKey: 'type' });
const nestedSchema = new mongoose.Schema({
body: {
children: [contentSchema],
},
});
const childrenArraySchema = nestedSchema.path('body.children') as mongoose.Schema.Types.DocumentArray;
childrenArraySchema.discriminator(
'container',
new mongoose.Schema({
body: { children: childrenArraySchema },
})
);
const Nested = mongoose.model<mongoose.Document>('nested', nestedSchema);
const nestedDocument = new Nested({
body: {
children: [
{ type: 'container', body: { children: [] } },
{
type: 'container',
body: {
children: [
{
type: 'container',
body: {
children: [{ type: 'container', body: { children: [] } }],
},
},
],
},
},
],
},
});
// ok with 5.10.2
// failes with 5.10.3+
expect(nestedDocument.toJSON()).toEqual({
_id: expect.toBeObject(),
body: {
children: [
{
_id: expect.toBeObject(),
type: 'container',
body: { children: [] },
},
{
_id: expect.toBeObject(),
type: 'container',
body: {
children: [
{
_id: expect.toBeObject(),
type: 'container',
// this gets lost:
body: {
children: [
{
_id: expect.toBeObject(),
type: 'container',
body: {
children: [],
},
},
],
},
},
],
},
},
],
},
});
});
What is the expected behavior?
Test should pass.
What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.
Looks like this was an unintended consequence of #9370. We'll fix this for v5.11.3.
However, your example doesn't quite line up exactly with the one in the discriminator docs. Our tests are passing for that example, the difference is that you're relying on adding the same document array schema type childrenArraySchema
to itself via a discriminator. The example in the docs instead relies on adding a schema (not a schema type) subEventSchema
to itself.
I'm not quite sure how to get your example to line up with how the docs does it - recursion is confusing. But your approach should work going forward.
Great, looking forward! Thank you very much!