-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Closed
Closed
Copy link
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.16.5
Node.js version
22.2.0
MongoDB server version
8.0.12
Typescript version (if applicable)
5.x.x
Description
Hi,
When i lean a mongoose document using
model.toObject({flattenObjectIds: true});
//or
model.toJSON({flattenObjectIds: true});
the return type is still
toObject: () => YourSchema & Required<{_id: Types.ObjectId}> & {__v: number}
which contains _id: Types.ObjectId
that should be _id: string
.
Same problem with versionKey: false
that should not return {__v: number}
.
*It should also work with those parameters in model definition:
const YourSchema = new Schema<YourSchema>({
//...
},{
toObject: {flattenObjectIds: true, versionKey: false}
})
Steps to Reproduce
Create an interface and a model:
interface ASchema {
_id: Types.ObjectId;
testProperty: number;
}
const ASchema = new Schema<ASchema>({
testProperty: Number
});
const AModel = model<ASchema>("YourModel", ASchema);
Register a new instance of the model and try to call toObject()
:
const a = new AModel({testProperty: 8});
const b: Omit<ASchema, "_id"> & {_id: string} = a.toObject({flattenObjectIds: true});
// Error on 'b': Types of property _id are incompatible. Type ObjectId is not assignable to type string
Expected Behavior
Return type should match the options:
toObject(): YourSchema & Required<{_id: Types.ObjectId}> & {__v: number};
toObject({flattenObjectIds: true}): YourSchema & Required<{_id: string}> & {__v: number};
toObject({versionKey: false}): YourSchema & Required<{_id: Types.ObjectId}>;
toObject({flattenObjectIds: true, versionKey: false}): YourSchema & Required<{_id: string}>;
Metadata
Metadata
Assignees
Labels
No labels