diff --git a/test/types/document.test.ts b/test/types/document.test.ts index 84451edf0f..cf45b9ce85 100644 --- a/test/types/document.test.ts +++ b/test/types/document.test.ts @@ -359,3 +359,51 @@ function gh13738() { expectType(person.get('dob')); expectType<{ theme: string; alerts: { sms: boolean } }>(person.get('settings')); } + +async function gh14876() { + type CarObjectInterface = { + make: string; + model: string; + year: number; + owner: Types.ObjectId; + }; + const carSchema = new Schema({ + make: { type: String, required: true }, + model: { type: String, required: true }, + year: { type: Number, required: true }, + owner: { type: Schema.Types.ObjectId, ref: 'User' } + }); + + type UserObjectInterface = { + name: string; + age: number; + }; + const userSchema = new Schema({ + name: String, + age: Number + }); + + const Car = model('Car', carSchema); + const User = model('User', userSchema); + + const user = await User.create({ name: 'John', age: 25 }); + const car = await Car.create({ + make: 'Toyota', + model: 'Camry', + year: 2020, + owner: user._id + }); + + const populatedCar = await Car.findById(car._id) + .populate<{ owner: UserObjectInterface }>('owner') + .exec(); + + if (!populatedCar) return; + + console.log(populatedCar.owner.name); // outputs John + + const depopulatedCar = populatedCar.depopulate<{ owner: Types.ObjectId }>('owner'); + + expectType(populatedCar.owner); + expectType(depopulatedCar.owner); +} diff --git a/types/document.d.ts b/types/document.d.ts index 5557269783..20f5de4c42 100644 --- a/types/document.d.ts +++ b/types/document.d.ts @@ -138,7 +138,7 @@ declare module 'mongoose' { * Takes a populated field and returns it to its unpopulated state. If called with * no arguments, then all populated fields are returned to their unpopulated state. */ - depopulate(path?: string | string[]): this; + depopulate(path?: string | string[]): MergeType; /** * Returns the list of paths that have been directly modified. A direct