Skip to content

Commit 7a88a6a

Browse files
committed
types(models): add cleaner type definitions for insertMany() with no generics to prevent errors when using insertMany() in generic classes
Fix #13957
1 parent 642abd1 commit 7a88a6a

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

test/types/models.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -709,3 +709,27 @@ async function gh13746() {
709709
expectType<ObjectId | undefined>(findOneAndUpdateRes.lastErrorObject?.upserted);
710710
expectType<OkType>(findOneAndUpdateRes.ok);
711711
}
712+
713+
function gh13957() {
714+
class RepositoryBase<T> {
715+
protected model: mongoose.Model<T>;
716+
717+
constructor(schemaModel: mongoose.Model<T>) {
718+
this.model = schemaModel;
719+
}
720+
721+
// Testing that the following compiles successfully
722+
async insertMany(elems: T[]): Promise<T[]> {
723+
elems = await this.model.insertMany(elems);
724+
return elems;
725+
}
726+
}
727+
728+
interface ITest {
729+
name?: string
730+
}
731+
const schema = new Schema({ name: String });
732+
const TestModel = model('Test', schema);
733+
const repository = new RepositoryBase<ITest>(TestModel);
734+
expectType<Promise<ITest[]>>(repository.insertMany([{ name: 'test' }]));
735+
}

types/models.d.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,34 @@ declare module 'mongoose' {
362362
init(): Promise<THydratedDocumentType>;
363363

364364
/** Inserts one or more new documents as a single `insertMany` call to the MongoDB server. */
365+
insertMany(
366+
docs: Array<TRawDocType>
367+
): Promise<Array<THydratedDocumentType>>;
368+
insertMany(
369+
docs: Array<TRawDocType>,
370+
options: InsertManyOptions & { lean: true; }
371+
): Promise<Array<Require_id<TRawDocType>>>;
372+
insertMany(
373+
doc: Array<TRawDocType>,
374+
options: InsertManyOptions & { ordered: false; rawResult: true; }
375+
): Promise<mongodb.InsertManyResult<Require_id<TRawDocType>> & {
376+
mongoose: {
377+
validationErrors: Error[];
378+
results: Array<
379+
Error |
380+
Object |
381+
THydratedDocumentType
382+
>
383+
}
384+
}>;
385+
insertMany(
386+
docs: Array<TRawDocType>,
387+
options: InsertManyOptions & { lean: true, rawResult: true; }
388+
): Promise<mongodb.InsertManyResult<Require_id<TRawDocType>>>;
389+
insertMany(
390+
docs: Array<TRawDocType>,
391+
options: InsertManyOptions & { rawResult: true; }
392+
): Promise<mongodb.InsertManyResult<Require_id<THydratedDocumentType>>>;
365393
insertMany<DocContents = TRawDocType>(
366394
docs: Array<DocContents | TRawDocType>,
367395
options: InsertManyOptions & { lean: true; }

0 commit comments

Comments
 (0)