-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Open
Labels
enhancementThis issue is a user-facing general improvement that doesn't fix a bug or add a new featureThis issue is a user-facing general improvement that doesn't fix a bug or add a new featuretypescriptTypes or Types-test related issue / Pull RequestTypes or Types-test related issue / Pull Request
Milestone
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.17.2
Node.js version
22.2.0
MongoDB server version
6.18.0
Typescript version (if applicable)
5.9.2
Description
Hi, thanks you for providing a fix for #15578 , unfortunately, the bug was not fully resolved
The default configurations for function toObject()
and toJSON()
declared in schemas definition should also propagate and alter return types.
Steps to Reproduce
import {model, Schema, Types} from "mongoose";
// Creating an interface for our schema
interface ASchema {
_id: Types.ObjectId;
testId: Types.ObjectId;
testProperty: number;
}
const ASchema = new Schema<ASchema>({
testProperty: Number,
testId: Types.ObjectId,
},
// Setting global parameters in the schema definition
{
toObject: {flattenObjectIds: true, versionKey: false},
toJSON: {flattenObjectIds: true, versionKey: false}
}
);
const AModel = model<ASchema>("YourModel", ASchema);
const document = new AModel({testProperty: 8, testId: new Types.ObjectId()});
// Theses types are correct since https://github.com/Automattic/mongoose/issues/15578
const a: Omit<ASchema, "_id" | "testId"> & { _id: string, testId: string } = document.toObject({flattenObjectIds: true});
const b: Omit<ASchema, "_id" | "testId"> & { _id: string, testId: string } = document.toJSON({flattenObjectIds: true});
// But types should match also without function parameter if they were defined in the schema definition.
const c: Omit<ASchema, "_id" | "testId"> & { _id: string, testId: string } = document.toObject();
// TS2322: Types of property _id are incompatible. Type ObjectId is not assignable to type string.
const d: Omit<ASchema, "_id" | "testId"> & { _id: string, testId: string } = document.toJSON();
// TS2322: Types of property _id are incompatible. Type ObjectId is not assignable to type string.
Expected Behavior
- Function
toObject()
should also return ...& {_id: string}
... if Schema option containtoObject: {flattenObjectIds: true},
as inASchema
. - Function
toObject()
should also returnOmit<..., "__v">
if Schema option containtoObject: {versionKey: false},
as inASchema
.
Same for function toJSON()
.
Metadata
Metadata
Assignees
Labels
enhancementThis issue is a user-facing general improvement that doesn't fix a bug or add a new featureThis issue is a user-facing general improvement that doesn't fix a bug or add a new featuretypescriptTypes or Types-test related issue / Pull RequestTypes or Types-test related issue / Pull Request