Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

types(document): add generic param to depopulate() to allow updating properties #14891

Merged
merged 1 commit into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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