Skip to content

Commit 7f0d4ce

Browse files
authored
Merge pull request #15413 from Automattic/vkarpov15/gh-15412
types(schema): allow post('init')
2 parents 2dda096 + 484eb72 commit 7f0d4ce

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

test/types/schema.test.ts

+18-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ import {
2222
Query,
2323
model,
2424
ValidateOpts,
25-
BufferToBinary
25+
BufferToBinary,
26+
CallbackWithoutResultAndOptionalError
2627
} from 'mongoose';
2728
import { Binary } from 'mongodb';
2829
import { IsPathRequired } from '../../types/inferschematype';
@@ -1778,6 +1779,22 @@ function gh15301() {
17781779
});
17791780
}
17801781

1782+
function gh15412() {
1783+
const ScheduleEntrySchema = new Schema({
1784+
startDate: { type: Date, required: true },
1785+
endDate: { type: Date, required: false }
1786+
});
1787+
const ScheduleEntry = model('ScheduleEntry', ScheduleEntrySchema);
1788+
1789+
type ScheduleEntryDoc = ReturnType<typeof ScheduleEntry['hydrate']>
1790+
1791+
ScheduleEntrySchema.post('init', function(this: ScheduleEntryDoc, _res: any, next: CallbackWithoutResultAndOptionalError) {
1792+
expectType<Date>(this.startDate);
1793+
expectType<Date | null | undefined>(this.endDate);
1794+
next();
1795+
});
1796+
}
1797+
17811798
function defaultReturnsUndefined() {
17821799
const schema = new Schema<{ arr: number[] }>({
17831800
arr: {

types/index.d.ts

+2
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,8 @@ declare module 'mongoose' {
387387
post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: PostMiddlewareFunction<T, T>): this;
388388
post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions & SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
389389
post<T = THydratedDocumentType>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: false }, fn: PostMiddlewareFunction<T, T>): this;
390+
post<T = THydratedDocumentType>(method: 'init', fn: PostMiddlewareFunction<T, T>): this;
391+
390392
// this = Query
391393
post<T = Query<any, any>>(method: MongooseRawResultQueryMiddleware|MongooseRawResultQueryMiddleware[], fn: PostMiddlewareFunction<T, null | QueryResultType<T> | ModifyResult<QueryResultType<T>>>): this;
392394
post<T = Query<any, any>>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;

0 commit comments

Comments
 (0)