Skip to content

Commit

Permalink
Merge pull request #14891 from Automattic/vkarpov15/gh-14876
Browse files Browse the repository at this point in the history
types(document): add generic param to depopulate() to allow updating properties
  • Loading branch information
vkarpov15 authored Sep 17, 2024
2 parents 1b18d5b + 78623ba commit 90f8af3
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
48 changes: 48 additions & 0 deletions test/types/document.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,3 +359,51 @@ function gh13738() {
expectType<Date>(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<CarObjectInterface>({
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<UserObjectInterface>({
name: String,
age: Number
});

const Car = model<CarObjectInterface>('Car', carSchema);
const User = model<UserObjectInterface>('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<UserObjectInterface>(populatedCar.owner);
expectType<Types.ObjectId>(depopulatedCar.owner);
}
2 changes: 1 addition & 1 deletion types/document.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Paths = {}>(path?: string | string[]): MergeType<this, Paths>;

/**
* Returns the list of paths that have been directly modified. A direct
Expand Down

0 comments on commit 90f8af3

Please sign in to comment.