Skip to content

toObject() and toJSON() schemas options should propagate #15594

@Gagafeee

Description

@Gagafeee

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 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().

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementThis issue is a user-facing general improvement that doesn't fix a bug or add a new featuretypescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions