Skip to content

Commit 9524f89

Browse files
committed
fix(types): make $addToSet fields mutable to allow programatically constructing $addToSet
Fix #12091
1 parent 201071b commit 9524f89

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

test/types/queries.test.ts

+14
Original file line numberDiff line numberDiff line change
@@ -325,5 +325,19 @@ function gh11964() {
325325
/* ... */
326326
}
327327
}
328+
}
328329

330+
function gh12091() {
331+
interface IUser{
332+
friendsNames: string[];
333+
}
334+
const userSchema = new Schema<IUser>({
335+
friendsNames: [String]
336+
});
337+
338+
const update: UpdateQuery<IUser> = { $addToSet: { friendsNames: 'John Doe' } };
339+
if (!update?.$addToSet) {
340+
return;
341+
}
342+
update.$addToSet.friendsNames = 'Jane Doe';
329343
}

types/index.d.ts

+7-3
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,10 @@ declare module 'mongoose' {
437437

438438
export type SortOrder = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
439439

440+
type Mutable<T> = {
441+
-readonly [K in keyof T]: T[K];
442+
}
443+
440444
type _UpdateQuery<TSchema> = {
441445
/** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */
442446
$currentDate?: AnyKeys<TSchema> & AnyObject;
@@ -450,10 +454,10 @@ declare module 'mongoose' {
450454
$unset?: AnyKeys<TSchema> & AnyObject;
451455

452456
/** @see https://docs.mongodb.com/manual/reference/operator/update-array/ */
453-
$addToSet?: mongodb.SetFields<TSchema>;
457+
$addToSet?: Mutable<mongodb.SetFields<TSchema>>;
454458
$pop?: AnyKeys<TSchema> & AnyObject;
455-
$pull?: mongodb.PullOperator<TSchema>;
456-
$push?: mongodb.PushOperator<TSchema>;
459+
$pull?: Mutable<mongodb.PullOperator<TSchema>>;
460+
$push?: Mutable<mongodb.PushOperator<TSchema>>;
457461
$pullAll?: mongodb.PullAllOperator<TSchema>;
458462

459463
/** @see https://docs.mongodb.com/manual/reference/operator/update-bitwise/ */

0 commit comments

Comments
 (0)