-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Closed
Closed
Copy link
Labels
typescriptTypes or Types-test related issue / Pull RequestTypes or Types-test related issue / Pull Request
Milestone
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.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
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.Types.Subdocument<Names>;
};
type UserMethods = {
getName(): string;
};
type UserModelType = mongoose.Model<User, {}, UserMethods, {}, THydratedUserDocument>;
const userSchema = new mongoose.Schema<User, UserModelType, UserMethods>(
{
names: new mongoose.Schema<Names>({ firstName: String }),
},
{
methods: {
getName() {
// `this.names` is a subdocument, so we can call `toObject` on it
// -> However, there is a typing error "Property 'toObject' does not exist on type 'Names'."
return this.names.toObject();
},
},
}
);
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" } });
doc.names?.ownerDocument(); // Works, `names` is a subdocument!
}
run();
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.
Metadata
Metadata
Assignees
Labels
typescriptTypes or Types-test related issue / Pull RequestTypes or Types-test related issue / Pull Request