Skip to content

Commit

Permalink
types(document): add generic param to depopulate() to allow updating …
Browse files Browse the repository at this point in the history
…properties

Fix #14876
  • Loading branch information
vkarpov15 committed Sep 16, 2024
1 parent 1b18d5b commit 78623ba
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 78623ba

Please sign in to comment.