Skip to content

Commit 11c754c

Browse files
authored
Merge pull request #14581 from Automattic/vkarpov15/gh-14574
types(model+query): pass TInstanceMethods to QueryWithHelpers so populated docs have methods
2 parents d5202fb + e7d5c93 commit 11c754c

File tree

3 files changed

+173
-95
lines changed

3 files changed

+173
-95
lines changed

test/types/populate.test.ts

+41
Original file line numberDiff line numberDiff line change
@@ -419,3 +419,44 @@ function gh14441() {
419419
expectType<string>(docObject.child.name);
420420
});
421421
}
422+
423+
async function gh14574() {
424+
// Document definition
425+
interface User {
426+
firstName: string;
427+
lastName: string;
428+
friend?: Types.ObjectId;
429+
}
430+
431+
interface UserMethods {
432+
fullName(): string;
433+
}
434+
435+
type UserModelType = mongoose.Model<User, {}, UserMethods>;
436+
437+
const userSchema = new Schema<User, UserModelType, UserMethods>(
438+
{
439+
firstName: String,
440+
lastName: String,
441+
friend: { type: Schema.Types.ObjectId, ref: 'User' }
442+
},
443+
{
444+
methods: {
445+
fullName() {
446+
return `${this.firstName} ${this.lastName}`;
447+
}
448+
}
449+
}
450+
);
451+
const userModel = model<User, UserModelType>('User', userSchema);
452+
453+
const UserModel = () => userModel;
454+
455+
const user = await UserModel()
456+
.findOne({ firstName: 'b' })
457+
.populate<{ friend: HydratedDocument<User, UserMethods> }>('friend')
458+
.orFail()
459+
.exec();
460+
expectType<string>(user.fullName());
461+
expectType<string>(user.friend.fullName());
462+
}

0 commit comments

Comments
 (0)