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: add splice() to DocumentArray to allow adding partial objects with splice() #15085

Merged
merged 1 commit into from
Dec 11, 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
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
Loading