-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Document.prototype.toObject() with discriminators returns all fields and selectively applies getters #15218
Comments
Unfortunately this is expected behavior, although I admit the fact that The issue is that the following update does not unset await TestModel.updateOne(
{ _id: cd._id },
{
key: type2Key,
field2,
},
{overwriteDiscriminatorKey: true},
); You can see the issue more clearly if you add a field that isn't in any schema in this await TestModel.updateOne(
{ _id: cd._id },
{
key: type2Key,
field2,
field3: 'taco'
},
{overwriteDiscriminatorKey: true, strict: false},
);
// Later
cd2.field3; // undefined
cd2.get('field3'); // 'taco'
cd2.toObject().field3; // 'taco' Your best bet would be to explicitly unset await TestModel.updateOne(
{ _id: cd._id },
{
$set: { key: type2Key, field2 },
$unset: { field1: 1 }
},
{overwriteDiscriminatorKey: true, strict: false},
); We will take a closer look at #5159 for our next major release. |
If I log
Above, Lines 4176 to 4178 in 16d2407
Could similar logic be applied in |
The fact that We could add a |
That would be helpful, yes! |
fix: infer discriminator key if set in `$set` with overwriteDiscriminatorKey
I would still recommend running a migration to unset the unexpected fields in MongoDB |
Prerequisites
Mongoose version
8.9.7
Node.js version
20.18.0
MongoDB server version
8.0.4
Typescript version (if applicable)
No response
Description
After updating a discriminator key in a document with schema discriminators and getters, the Document includes the fields for the current discriminator, as expected. However, Document.toObject() returns all fields, including those defined in a different discriminator schema, but only applies getters to the fields matching the current discriminator.
Steps to Reproduce
The following script will fail when checking the discriminator fields. In particular, the Document contains only the fields relevant to the discriminator, but the object returned by Document.toObject() contains all fields, including those for the other discriminator schema.
Expected Behavior
As shown in the script above, since a Document with a discriminator includes only the fields relevant to the currently set discriminator key (prior to calling toObject()), I would expect the object returned by toObject() to also only include those fields defined in that discriminator schema.
If all fields must be returned by toObject() (even those not relevant to the current discriminator schema) I would expect all getters to have been called.
The text was updated successfully, but these errors were encountered: