Skip to content

Commit

Permalink
Merge pull request #15085 from Automattic/vkarpov15/gh-15041
Browse files Browse the repository at this point in the history
types: add splice() to DocumentArray to allow adding partial objects with splice()
  • Loading branch information
vkarpov15 authored Dec 11, 2024
2 parents 36fb91a + 3ef8901 commit 891931b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
17 changes: 17 additions & 0 deletions test/types/docArray.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,20 @@ function gh14469() {
const jsonNames = doc?.names[0]?.toJSON();
expectType<string>(jsonNames?.firstName);
}

function gh15041() {
const subDoc = {
name: { type: String, required: true },
age: { type: Number, required: true }
};

const testSchema = new Schema({
subdocArray: { type: [subDoc], required: true }
});

const TestModel = model('Test', testSchema);

const doc = new TestModel({ subdocArray: [{ name: 'John', age: 30 }] });
type TestModelDoc = ReturnType<(typeof TestModel)['hydrate']>
expectType<TestModelDoc['subdocArray'][0][]>(doc.subdocArray.splice(0, 1, { name: 'Bill' }));
}
8 changes: 5 additions & 3 deletions types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,19 +60,21 @@ declare module 'mongoose' {

class Decimal128 extends mongodb.Decimal128 { }

class DocumentArray<T> extends Types.Array<T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>, any, T> & T> {
class DocumentArray<T, THydratedDocumentType extends Types.Subdocument<any> = Types.Subdocument<InferId<T>, any, T> & T> extends Types.Array<THydratedDocumentType> {
/** DocumentArray constructor */
constructor(values: AnyObject[]);

isMongooseDocumentArray: true;

/** Creates a subdocument casted to this schema. */
create(obj: any): T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>> & T;
create(obj: any): THydratedDocumentType;

/** Searches array items for the first document with a matching _id. */
id(id: any): (T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>> & T) | null;
id(id: any): THydratedDocumentType | null;

push(...args: (AnyKeys<T> & AnyObject)[]): number;

splice(start: number, deleteCount?: number, ...args: (AnyKeys<T> & AnyObject)[]): THydratedDocumentType[];
}

class Map<V> extends global.Map<string, V> {
Expand Down

0 comments on commit 891931b

Please sign in to comment.