Prerequisites
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 contain toObject: {flattenObjectIds: true}, as in ASchema.
- Function
toObject() should also return Omit<..., "__v"> if Schema option contain toObject: {versionKey: false}, as in ASchema.
Same for function toJSON().
Prerequisites
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()andtoJSON()declared in schemas definition should also propagate and alter return types.Steps to Reproduce
Expected Behavior
toObject()should also return ...& {_id: string}... if Schema option containtoObject: {flattenObjectIds: true},as inASchema.toObject()should also returnOmit<..., "__v">if Schema option containtoObject: {versionKey: false},as inASchema.Same for function
toJSON().