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


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


Expected Behavior
Both obj2 and obj3 should have proper types
Metadata
Metadata
Assignees
Labels
No labels