Skip to content

Commit

Permalink
Merge pull request #14581 from Automattic/vkarpov15/gh-14574
Browse files Browse the repository at this point in the history
types(model+query): pass TInstanceMethods to QueryWithHelpers so populated docs have methods
  • Loading branch information
vkarpov15 committed May 9, 2024
2 parents d5202fb + e7d5c93 commit 11c754c
Show file tree
Hide file tree
Showing 3 changed files with 173 additions and 95 deletions.
41 changes: 41 additions & 0 deletions test/types/populate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,3 +419,44 @@ function gh14441() {
expectType<string>(docObject.child.name);
});
}

async function gh14574() {
// Document definition
interface User {
firstName: string;
lastName: string;
friend?: Types.ObjectId;
}

interface UserMethods {
fullName(): string;
}

type UserModelType = mongoose.Model<User, {}, UserMethods>;

const userSchema = new Schema<User, UserModelType, UserMethods>(
{
firstName: String,
lastName: String,
friend: { type: Schema.Types.ObjectId, ref: 'User' }
},
{
methods: {
fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
}
);
const userModel = model<User, UserModelType>('User', userSchema);

const UserModel = () => userModel;

const user = await UserModel()
.findOne({ firstName: 'b' })
.populate<{ friend: HydratedDocument<User, UserMethods> }>('friend')
.orFail()
.exec();
expectType<string>(user.fullName());
expectType<string>(user.friend.fullName());
}

0 comments on commit 11c754c

Please sign in to comment.