Skip to content

Breaking types of toObject on SubDocument or ArraySubdocument #14601

Closed
@piyushk96

Description

@piyushk96

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.3.4

Node.js version

20

MongoDB server version

6.6

Typescript version (if applicable)

5.4.5

Description

Since Mongoose v7, the type of the results obtained by calling toObject on SubDocument or ArraySubdocument is any. Prior to v7 toObject return type was working fine.

Steps to Reproduce

** Code for version >=v7 **

import mongoose, { Types, model } from 'mongoose';
const { Schema } = mongoose;

mongoose.connect('mongodb://localhost:27017/testdb');

interface ISub {
  field1: string;
}
interface IMain {
  f1: string;
  f2: ISub & Types.Subdocument;
  f3: (ISub & Types.ArraySubdocument)[];
}

const subSchema = new Schema({ field1: String }, { _id: false });

const mainSchema = new Schema({
  f1: String,
  f2: { type: subSchema },
  f3: { type: [subSchema] }
})
const MainModel = model<IMain>("Main", mainSchema);

const item = new MainModel({
  f1: "test",
  f2: { field1: "test" },
  f3: [{ field1: "test" }]
})

const obj = item.toObject();

const obj2 = item.f2.toObject()
image image

** Code for version < v7 **

import mongoose, { Types, model, Document } from 'mongoose';
const { Schema } = mongoose;

mongoose.connect('mongodb://localhost:27017/testdb');

interface ISub {
  field1: string;
}
interface IMain {
  f1: string;
  f2: ISub & Types.Subdocument;
  f3: (ISub & Types.ArraySubdocument)[];
}

type IMainDoc = IMain & Document;

const subSchema = new Schema({ field1: String }, { _id: false });

const mainSchema = new Schema({
  f1: String,
  f2: { type: subSchema },
  f3: { type: [subSchema] }
})
const MainModel = model<IMainDoc>("Main", mainSchema);

const item = new MainModel({
  f1: "test",
  f2: { field1: "test" },
  f3: [{ field1: "test" }]
})

const obj = item.toObject();

const obj2 = item.f2.toObject()
const obj3 = item.f3[0].toObject()
image image

Expected Behavior

Both obj2 and obj3 should have proper types

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions