EntityRepository <T>
Hierarchy
- EntityRepository<T>
- EntityRepository
Index
Constructors
constructor
Parameters
em: MongoEntityManager<MongoDriver>
entityName: EntityName<T>
Returns MongoEntityRepository<T>
Methods
aggregate
Parameters
pipeline: any[]
Returns Promise<any[]>
inheritedassign
Shortcut for
wrap(entity).assign(data, { em })Parameters
entity: Ent | Partial<Ent>
data: Data & IsSubset<EntityData<Naked, Convert>, Data>
optionaloptions: AssignOptions<Convert>
Returns MergeSelected<Ent, Naked, keyof Data & string>
inheritedcanPopulate
Checks whether given property can be populated on the entity.
Parameters
property: string
Returns boolean
inheritedcount
Returns total number of entities matching your
wherequery.Parameters
where: FilterQuery<T> = ...
options: CountOptions<T, Hint> = {}
Returns Promise<number>
inheritedcreate
Creates new instance of given entity and populates it with given data. The entity constructor will be used unless you provide
{ managed: true }in theoptionsparameter. The constructor will be given parameters based on the defined constructor of the entity. If the constructor parameter matches a property name, its value will be extracted fromdata. If no matching property exists, the wholedataparameter will be passed. This means we can also defineconstructor(data: Partial<T>)andem.create()will pass the data into it (unless we have a property nameddatatoo).The parameters are strictly checked, you need to provide all required properties. You can use
OptionalPropssymbol to omit some properties from this check without making them optional. Alternatively, usepartial: truein the options to disable the strict checks for required properties. This option has no effect on runtime.The newly created entity will be automatically marked for persistence via
em.persistunless you disable this behavior, either locally viapersist: falseoption, or globally viapersistOnCreateORM config option.Parameters
data: RequiredEntityData<T, never, Convert>
optionaloptions: CreateOptions<Convert>
Returns T
inheritedfind
Finds all entities matching your
wherequery. You can pass additional options via theoptionsparameter.Parameters
where: FilterQuery<T>
optionaloptions: FindOptions<T, Hint, Fields, Excludes>
Returns Promise<Loaded<T, Hint, Fields, Excludes>[]>
inheritedfindAll
Finds all entities of given type. You can pass additional options via the
optionsparameter.Parameters
optionaloptions: FindAllOptions<T, Hint, Fields, Excludes>
Returns Promise<Loaded<T, Hint, Fields, Excludes>[]>
inheritedfindAndCount
Calls
em.find()andem.count()with the same arguments (where applicable) and returns the results as tuple where first element is the array of entities, and the second is the count.Parameters
where: FilterQuery<T>
optionaloptions: FindOptions<T, Hint, Fields, Excludes>
Returns Promise<[Loaded<T, Hint, Fields, Excludes>[], number]>
inheritedfindByCursor
Calls
em.find()andem.count()with the same arguments (where applicable) and returns the results as Cursor object. Supportsbefore,after,firstandlastoptions while disallowinglimitandoffset. ExplicitorderByoption is required.Use
firstandafterfor forward pagination, orlastandbeforefor backward pagination.firstandlastare numbers and serve as an alternative tooffset, those options are mutually exclusive, use only one at a timebeforeandafterspecify the previous cursor value, it can be one of the:Cursorinstance- opaque string provided by
startCursor/endCursorproperties - POJO/entity instance
const currentCursor = await em.findByCursor(User, {}, {
first: 10,
after: previousCursor, // cursor instance
orderBy: { id: 'desc' },
});
// to fetch next page
const nextCursor = await em.findByCursor(User, {}, {
first: 10,
after: currentCursor.endCursor, // opaque string
orderBy: { id: 'desc' },
});
// to fetch next page
const nextCursor2 = await em.findByCursor(User, {}, {
first: 10,
after: { id: lastSeenId }, // entity-like POJO
orderBy: { id: 'desc' },
});The options also support an
includeCount(true by default) option. If set to false, thetotalCountis not returned as part of the cursor. This is useful for performance reason, when you don't care about the total number of pages.The
Cursorobject provides the following interface:Cursor<User> {
items: [
User { ... },
User { ... },
User { ... },
],
totalCount: 50, // not included if `includeCount: false`
startCursor: 'WzRd',
endCursor: 'WzZd',
hasPrevPage: true,
hasNextPage: true,
}Parameters
where: FilterQuery<T>
options: FindByCursorOptions<T, Hint, Fields, Excludes, true>
Returns Promise<Cursor<T, Hint, Fields, Excludes, true>>
inheritedfindOne
Finds first entity matching your
wherequery.Parameters
where: FilterQuery<T>
optionaloptions: FindOneOptions<T, Hint, Fields, Excludes>
Returns Promise<null | Loaded<T, Hint, Fields, Excludes>>
inheritedfindOneOrFail
Finds first entity matching your
wherequery. If nothing is found, it will throw an error. You can override the factory for creating this method viaoptions.failHandlerlocally or viaConfiguration.findOneOrFailHandlerglobally.Parameters
where: FilterQuery<T>
optionaloptions: FindOneOrFailOptions<T, Hint, Fields, Excludes>
Returns Promise<Loaded<T, Hint, Fields, Excludes>>
getCollection
Returns Collection<T>
getEntityManager
Returns the underlying EntityManager instance
Returns MongoEntityManager<MongoDriver>
inheritedgetEntityName
Returns string
inheritedgetReference
Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
Parameters
id: T extends { [PrimaryKeyProp]?: PK } ? PK extends keyof T<T> ? ReadonlyPrimary<UnwrapPrimary<T<T>[PK<PK>]>> : PK extends keyof T<T>[] ? ReadonlyPrimary<PrimaryPropToType<T<T>, PK<PK>>> : PK : T extends { _id?: PK } ? string | ReadonlyPrimary<PK> : T extends { uuid?: PK } ? ReadonlyPrimary<PK> : T extends { id?: PK } ? ReadonlyPrimary<PK> : T
options: Omit<GetReferenceOptions, wrapped> & { wrapped: true }
Returns Ref<T>
inheritedinsert
Fires native insert query. Calling this has no side effects on the context (identity map).
Parameters
data: T | RequiredEntityData<T>
optionaloptions: NativeInsertUpdateOptions<T>
Returns Promise<T extends { [PrimaryKeyProp]?: PK } ? PK extends keyof T<T> ? ReadonlyPrimary<UnwrapPrimary<T<T>[PK<PK>]>> : PK extends keyof T<T>[] ? ReadonlyPrimary<PrimaryPropToType<T<T>, PK<PK>>> : PK : T extends { _id?: PK } ? string | ReadonlyPrimary<PK> : T extends { uuid?: PK } ? ReadonlyPrimary<PK> : T extends { id?: PK } ? ReadonlyPrimary<PK> : T>
inheritedinsertMany
Fires native insert query. Calling this has no side effects on the context (identity map).
Parameters
data: T[] | RequiredEntityData<T>[]
optionaloptions: NativeInsertUpdateOptions<T>
Returns Promise<(T extends { [PrimaryKeyProp]?: PK } ? PK extends keyof T<T> ? ReadonlyPrimary<UnwrapPrimary<T<T>[PK<PK>]>> : PK extends keyof T<T>[] ? ReadonlyPrimary<PrimaryPropToType<T<T>, PK<PK>>> : PK : T extends { _id?: PK } ? string | ReadonlyPrimary<PK> : T extends { uuid?: PK } ? ReadonlyPrimary<PK> : T extends { id?: PK } ? ReadonlyPrimary<PK> : T)[]>
inheritedmap
Maps raw database result to an entity and merges it to this EntityManager.
Parameters
result: EntityDictionary<T>
optionaloptions: { schema?: string }
optionalschema: string
Returns T
inheritedmerge
Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities via second parameter. By default it will return already loaded entities without modifying them.
Parameters
data: T | EntityData<T>
optionaloptions: MergeOptions
Returns T
inheritednativeDelete
Fires native delete query. Calling this has no side effects on the context (identity map).
Parameters
where: FilterQuery<T>
optionaloptions: DeleteOptions<T>
Returns Promise<number>
inheritednativeUpdate
Fires native update query. Calling this has no side effects on the context (identity map).
Parameters
where: FilterQuery<T>
data: EntityData<T>
optionaloptions: UpdateOptions<T>
Returns Promise<number>
inheritedpopulate
Loads specified relations in batch. This will execute one query for each relation, that will populate it on all the specified entities.
Parameters
entities: Ent
populate: false | AutoPath<Naked, Hint, ALL, 9>[]
optionaloptions: EntityLoaderOptions<Naked, Fields, Excludes>
Returns Promise<Ent extends object[] ? MergeLoaded<ArrayElement<Ent<Ent>>, Naked, Hint, Fields, Excludes, false>[] : MergeLoaded<Ent, Naked, Hint, Fields, Excludes, false>>
inheritedupsert
Creates or updates the entity, based on whether it is already present in the database. This method performs an
insert on conflict mergequery ensuring the database is in sync, returning a managed entity instance. The method accepts eitherentityNametogether with the entitydata, or just entity instance.// insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
const author = await em.getRepository(Author).upsert({ email: 'foo@bar.com', age: 33 });The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where
Author.emailis a unique property:// insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
// select "id" from "author" where "email" = 'foo@bar.com'
const author = await em.getRepository(Author).upsert({ email: 'foo@bar.com', age: 33 });Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the
data.If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit
flushwill be required for those changes to be persisted.Parameters
optionalentityOrData: T | EntityData<T>
optionaloptions: UpsertOptions<T, Fields>
Returns Promise<T>
inheritedupsertMany
Creates or updates the entity, based on whether it is already present in the database. This method performs an
insert on conflict mergequery ensuring the database is in sync, returning a managed entity instance.// insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
const authors = await em.getRepository(Author).upsertMany([{ email: 'foo@bar.com', age: 33 }, ...]);The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where
Author.emailis a unique property:// insert into "author" ("age", "email") values (33, 'foo@bar.com'), (666, 'lol@lol.lol') on conflict ("email") do update set "age" = excluded."age"
// select "id" from "author" where "email" = 'foo@bar.com'
const author = await em.getRepository(Author).upsertMany([
{ email: 'foo@bar.com', age: 33 },
{ email: 'lol@lol.lol', age: 666 },
]);Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the
data.If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit
flushwill be required for those changes to be persisted.Parameters
optionalentitiesOrData: EntityData<T>[] | T[]
optionaloptions: UpsertManyOptions<T, Fields>
Returns Promise<T[]>
Shortcut to driver's aggregate method. Available in MongoDriver only.