Skip to content

Commit

Permalink
types(models): add cleaner type definitions for insertMany() with n…
Browse files Browse the repository at this point in the history
…o generics to prevent errors when using `insertMany()` in generic classes

Fix #13957
  • Loading branch information
vkarpov15 committed Oct 10, 2023
1 parent 642abd1 commit 7a88a6a
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
24 changes: 24 additions & 0 deletions test/types/models.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -709,3 +709,27 @@ async function gh13746() {
expectType<ObjectId | undefined>(findOneAndUpdateRes.lastErrorObject?.upserted);
expectType<OkType>(findOneAndUpdateRes.ok);
}

function gh13957() {
class RepositoryBase<T> {
protected model: mongoose.Model<T>;

constructor(schemaModel: mongoose.Model<T>) {
this.model = schemaModel;
}

// Testing that the following compiles successfully
async insertMany(elems: T[]): Promise<T[]> {
elems = await this.model.insertMany(elems);
return elems;
}
}

interface ITest {
name?: string
}
const schema = new Schema({ name: String });
const TestModel = model('Test', schema);
const repository = new RepositoryBase<ITest>(TestModel);
expectType<Promise<ITest[]>>(repository.insertMany([{ name: 'test' }]));
}
28 changes: 28 additions & 0 deletions types/models.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,34 @@ declare module 'mongoose' {
init(): Promise<THydratedDocumentType>;

/** Inserts one or more new documents as a single `insertMany` call to the MongoDB server. */
insertMany(
docs: Array<TRawDocType>
): Promise<Array<THydratedDocumentType>>;
insertMany(
docs: Array<TRawDocType>,
options: InsertManyOptions & { lean: true; }
): Promise<Array<Require_id<TRawDocType>>>;
insertMany(
doc: Array<TRawDocType>,
options: InsertManyOptions & { ordered: false; rawResult: true; }
): Promise<mongodb.InsertManyResult<Require_id<TRawDocType>> & {
mongoose: {
validationErrors: Error[];
results: Array<
Error |
Object |
THydratedDocumentType
>
}
}>;
insertMany(
docs: Array<TRawDocType>,
options: InsertManyOptions & { lean: true, rawResult: true; }
): Promise<mongodb.InsertManyResult<Require_id<TRawDocType>>>;
insertMany(
docs: Array<TRawDocType>,
options: InsertManyOptions & { rawResult: true; }
): Promise<mongodb.InsertManyResult<Require_id<THydratedDocumentType>>>;
insertMany<DocContents = TRawDocType>(
docs: Array<DocContents | TRawDocType>,
options: InsertManyOptions & { lean: true; }
Expand Down

0 comments on commit 7a88a6a

Please sign in to comment.