Skip to content

Commit 90f8af3

Browse files
authored
Merge pull request #14891 from Automattic/vkarpov15/gh-14876
types(document): add generic param to depopulate() to allow updating properties
2 parents 1b18d5b + 78623ba commit 90f8af3

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

test/types/document.test.ts

+48
Original file line numberDiff line numberDiff line change
@@ -359,3 +359,51 @@ function gh13738() {
359359
expectType<Date>(person.get('dob'));
360360
expectType<{ theme: string; alerts: { sms: boolean } }>(person.get('settings'));
361361
}
362+
363+
async function gh14876() {
364+
type CarObjectInterface = {
365+
make: string;
366+
model: string;
367+
year: number;
368+
owner: Types.ObjectId;
369+
};
370+
const carSchema = new Schema<CarObjectInterface>({
371+
make: { type: String, required: true },
372+
model: { type: String, required: true },
373+
year: { type: Number, required: true },
374+
owner: { type: Schema.Types.ObjectId, ref: 'User' }
375+
});
376+
377+
type UserObjectInterface = {
378+
name: string;
379+
age: number;
380+
};
381+
const userSchema = new Schema<UserObjectInterface>({
382+
name: String,
383+
age: Number
384+
});
385+
386+
const Car = model<CarObjectInterface>('Car', carSchema);
387+
const User = model<UserObjectInterface>('User', userSchema);
388+
389+
const user = await User.create({ name: 'John', age: 25 });
390+
const car = await Car.create({
391+
make: 'Toyota',
392+
model: 'Camry',
393+
year: 2020,
394+
owner: user._id
395+
});
396+
397+
const populatedCar = await Car.findById(car._id)
398+
.populate<{ owner: UserObjectInterface }>('owner')
399+
.exec();
400+
401+
if (!populatedCar) return;
402+
403+
console.log(populatedCar.owner.name); // outputs John
404+
405+
const depopulatedCar = populatedCar.depopulate<{ owner: Types.ObjectId }>('owner');
406+
407+
expectType<UserObjectInterface>(populatedCar.owner);
408+
expectType<Types.ObjectId>(depopulatedCar.owner);
409+
}

types/document.d.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ declare module 'mongoose' {
138138
* Takes a populated field and returns it to its unpopulated state. If called with
139139
* no arguments, then all populated fields are returned to their unpopulated state.
140140
*/
141-
depopulate(path?: string | string[]): this;
141+
depopulate<Paths = {}>(path?: string | string[]): MergeType<this, Paths>;
142142

143143
/**
144144
* Returns the list of paths that have been directly modified. A direct

0 commit comments

Comments
 (0)