-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Accessing the .toObject() of a subdocument inside of a method raises a typing error #14573
Comments
You also need to set import mongoose, { Types } from "mongoose";
// Subdocument definition
interface Names {
_id: Types.ObjectId;
firstName: string;
}
// Document definition
interface User {
names: Names;
}
// Define property overrides for hydrated documents
type THydratedUserDocument = {
names?: mongoose.HydratedSingleSubdocument<Names>;
};
type UserMethods = {
getName(): Names | undefined;
};
type UserModelType = mongoose.Model<User, {}, UserMethods, {}, THydratedUserDocument>;
const userSchema = new mongoose.Schema<
User,
UserModelType,
UserMethods,
{},
{},
{},
mongoose.DefaultSchemaOptions,
User,
THydratedUserDocument
>(
{
names: new mongoose.Schema<Names>({ firstName: String }),
},
{
methods: {
getName() {
const str: string | undefined = this.names?.firstName;
return this.names?.toObject(); // Works, `this.names` is a subdoc
},
},
}
);
const UserModel = mongoose.model<User, UserModelType>("User", userSchema);
async function run() {
await mongoose.connect("mongodb://localhost:27017");
await mongoose.connection.dropDatabase();
const doc = new UserModel({ names: { _id: "0".repeat(24), firstName: "foo" } });
const str: string | undefined = doc.names?.firstName;
doc.names?.ownerDocument(); // Works, `names` is a subdocument!
}
run(); |
@vkarpov15 Thank you for looking into it. While your example works, I still have two questions:
Would this be the right way?
|
In addition, even after the adjustment you suggested,
|
docs(typescript): clarify that setting THydratedDocumentType on schemas is necessary for correct method context
Prerequisites
Mongoose version
8.3.3
Node.js version
18.17.1
MongoDB server version
5
Typescript version (if applicable)
4.8
Description
I have followed the guide to create types for sub-documents in mongoose. While, the approach works in normal code flow, when i try to access the subdocument properties such as
.toObject
or.ownerDocument
inside a method it raises a typescript error.Steps to Reproduce
Expected Behavior
I would expect that there is no typing error when i try to access the subdocument props such as
.toObject
inside of a method.The text was updated successfully, but these errors were encountered: