Last active
March 30, 2021 17:03
-
-
Save OleksandrDanylchenko/ba42508a05e41d50dd111b37c7fec1de to your computer and use it in GitHub Desktop.
Mongoose Typescript general repository
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Document } from 'mongoose'; | |
export class BaseSchema extends Document {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { IsOptional, IsPositive } from 'class-validator'; | |
export class PaginationQuery { | |
@IsOptional() | |
@IsPositive() | |
limit: number; | |
@IsOptional() | |
@IsPositive() | |
offset: number; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
FilterQuery, | |
Model, | |
QueryFindOneAndRemoveOptions, | |
QueryFindOneAndUpdateOptions, | |
QueryPopulateOptions, | |
UpdateQuery | |
} from 'mongoose'; | |
import { BaseSchema } from '../schemas/base-schema.schema'; | |
import { PaginationQuery } from '../dtos/pagination-query'; | |
export class SchemaRepository<T extends BaseSchema> { | |
constructor(private readonly model: Model<T>) {} | |
async findOne( | |
modelFilterQuery: FilterQuery<T>, | |
modelPopulateOptions: QueryPopulateOptions[] = [] | |
): Promise<T> { | |
return this.model.findOne(modelFilterQuery).populate(modelPopulateOptions); | |
} | |
async find( | |
modelFilterQuery: FilterQuery<T>, | |
paginationQuery: PaginationQuery, | |
modelPopulateOptions: QueryPopulateOptions[] = [] | |
): Promise<T[]> { | |
return this.model | |
.find(modelFilterQuery) | |
.populate(modelPopulateOptions) | |
.skip(paginationQuery?.offset) | |
.limit(paginationQuery?.limit); | |
} | |
async create(newModel: T): Promise<T> { | |
const newModelInstance = new this.model(newModel); | |
return this.model.create(newModelInstance); | |
} | |
async findOneAndUpdate( | |
modelFilterQuery: FilterQuery<T>, | |
updateModel: UpdateQuery<T>, | |
updateOptions: QueryFindOneAndUpdateOptions = { new: true } | |
): Promise<T> { | |
return this.model.findOneAndUpdate( | |
modelFilterQuery, | |
updateModel, | |
updateOptions | |
); | |
} | |
async findOneAndDelete( | |
emitterFilterQuery: FilterQuery<T>, | |
updateOptions: QueryFindOneAndRemoveOptions = { projection: {} } | |
): Promise<T> { | |
return this.model.findOneAndDelete(emitterFilterQuery, updateOptions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment