Repository API
Repository API
manager- 该 repository 所使用的EntityManager。
const manager = repository.managermetadata- 该 repository 所管理实体的EntityMetadata。
const metadata = repository.metadataqueryRunner-EntityManager所使用的 query runner。仅在 EntityManager 的事务型实例中使用。
const queryRunner = repository.queryRunnertarget- 该 repository 所管理的目标实体类。仅在 EntityManager 的事务型实例中使用。
const target = repository.targetcreateQueryBuilder- 创建一个用于构建 SQL 查询的 query builder。进一步了解 QueryBuilder。
const users = await repository
.createQueryBuilder("user")
.where("user.name = :name", { name: "John" })
.getMany()hasId- 检查给定实体的主键列属性是否已定义。
if (repository.hasId(user)) {
// ... 做点什么
}getId- 获取给定实体的主键列属性值。如果实体有复合主键,返回值将是一个包含主键列名称与值的对象。
const userId = repository.getId(user) // userId === 1create- 创建一个新的User实例。可选地接受一个带用户属性的对象字面量,这些属性会被写入新建的 user 对象
const user = repository.create() // 等同于 const user = new User();
const user = repository.create({
id: 1,
firstName: "Timber",
lastName: "Saw",
}) // 等同于 const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";merge- 把多个实体合并进单个实体。
const user = new User()
repository.merge(user, { firstName: "Timber" }, { lastName: "Saw" }) // 等同于 user.firstName = "Timber"; user.lastName = "Saw";preload- 从给定的普通 javascript 对象创建一个新实体。如果该实体已存在于数据库中,它会加载它(以及与之相关的一切),用给定对象中的新值替换所有值,并返回这个新实体。这个新实体实际上是从数据库加载而来、其所有属性都被新对象替换后的实体。注意,给定的类实体对象必须带有实体 id / 主键,以便据此查找实体。如果找不到给定 id 的实体,返回 undefined。
const partialUser = {
id: 1,
firstName: "Rizzrak",
profile: {
id: 1,
},
}
const user = await repository.preload(partialUser)
// user 会包含 partialUser 中缺失的所有数据,其中属性值来自 partialUser:
// { id: 1, firstName: "Rizzrak", lastName: "Saw", profile: { id: 1, ... } }save- 保存给定实体或实体数组。如果实体已存在于数据库中,则更新它。如果实体不存在于数据库中,则插入它。它会在单个事务中保存所有给定实体(在 entity manager 本身不是事务型的情况下)。也支持部分更新,因为所有值为 undefined 的属性都会被跳过。返回被保存的实体。
await repository.save(user)
await repository.save([category1, category2, category3])remove- 移除给定实体或实体数组。它会在单个事务中移除所有给定实体(在 entity manager 本身不是事务型的情况下)。返回被移除的实体。
await repository.remove(user)
await repository.remove([category1, category2, category3])insert- 插入一个新实体或实体数组。
await repository.insert({
firstName: "Timber",
lastName: "Timber",
})
await repository.insert([
{
firstName: "Foo",
lastName: "Bar",
},
{
firstName: "Rizz",
lastName: "Rak",
},
])update- 按实体 id、多个 id 或给定条件更新实体。用提供的部分实体设置字段。
await repository.update({ age: 18 }, { category: "ADULT" })
// 执行 UPDATE user SET category = ADULT WHERE age = 18
await repository.update(1, { firstName: "Rizzrak" })
// 执行 UPDATE user SET firstName = Rizzrak WHERE id = 1
// 可选地请求 RETURNING / OUTPUT 返回值(仅受支持的驱动)
const result = await repository.update(
1,
{ firstName: "Rizzrak" },
{ returning: ["id", "firstName"] },
)
console.log(result.raw) // [{ id: 1, firstName: "Rizzrak" }]你可以传入一个条件对象数组,在一次调用中匹配多组不同的行(各条件之间是 OR 关系):
await repository.update([{ status: "expired" }, { flagged: true }], {
active: false,
})
// 执行 UPDATE user SET active = false WHERE status = 'expired' OR flagged = trueupdateAll- 更新目标类型的所有实体(不带 WHERE 子句)。用提供的部分实体设置字段。
await repository.updateAll({ category: "ADULT" })
// 执行 UPDATE user SET category = ADULT
await repository.updateAll(
{ category: "ADULT" },
{ returning: "*" }, // 仅限支持 returning 子句的驱动
)upsert- 插入一个新实体或实体数组;如果它们已存在,则改为更新。受 AuroraDataApi、Cockroach、Mysql、Postgres 和 Sqlite 数据库驱动支持。
当 upsert 操作因冲突而变成更新时,@UpdateDateColumn 和 @VersionColumn 这类特殊列会被自动更新为当前值。
用 update: false 标记的列,或被定义为计算生成列(通过 asExpression/generatedType)的列,永远不会被包含在冲突时的更新集合中。如果所有非冲突列都被这些规则排除(即没有可更新的列),该 upsert 会降级为"插入或忽略"操作,已存在的行保持完全不变。在支持冲突目标的数据库上(例如 PostgreSQL、CockroachDB),这限定在所指定的冲突列范围内;在 MySQL 系数据库上,使用的是 INSERT IGNORE,它对所有唯一约束生效。
await repository.upsert(
[
{ externalId: "abc123", firstName: "Rizzrak" },
{ externalId: "bca321", firstName: "Karzzir" },
],
["externalId"],
)
/** 执行
* INSERT INTO user
* VALUES
* (externalId = abc123, firstName = Rizzrak),
* (externalId = cba321, firstName = Karzzir),
* ON CONFLICT (externalId) DO UPDATE
* SET firstName = EXCLUDED.firstName,
* updatedDate = CURRENT_TIMESTAMP,
* version = version + 1
**/你也可以请求从 upsert 中返回值(在支持 RETURNING / OUTPUT 的驱动上可用):
const { raw } = await repository.upsert(
{ externalId: "abc123", firstName: "Rizzrak" },
{
conflictPaths: ["externalId"],
returning: ["externalId", "firstName"],
},
)
console.log(raw) // [{ externalId: "abc123", firstName: "Rizzrak" }]await repository.upsert(
[
{ externalId: "abc123", firstName: "Rizzrak" },
{ externalId: "bca321", firstName: "Karzzir" },
],
{
conflictPaths: ["externalId"],
skipUpdateIfNoValuesChanged: true, // postgres 支持,如果更新不会改变行数据则跳过更新
upsertType: "upsert", // "on-conflict-do-update" | "on-duplicate-key-update" | "upsert" —— 可选地指定 UpsertType;'upsert' 目前仅 CockroachDB 支持
},
)
/** 执行
* INSERT INTO user
* VALUES
* (externalId = abc123, firstName = Rizzrak),
* (externalId = cba321, firstName = Karzzir),
* ON CONFLICT (externalId) DO UPDATE
* SET firstName = EXCLUDED.firstName
* WHERE user.firstName IS DISTINCT FROM EXCLUDED.firstName
**/await repository.upsert(
[
{ externalId: "abc123", firstName: "Rizzrak", dateAdded: "2020-01-01" },
{ externalId: "bca321", firstName: "Karzzir", dateAdded: "2022-01-01" },
],
{
conflictPaths: ["externalId"],
skipUpdateIfNoValuesChanged: true, // postgres 支持,如果更新不会改变行数据则跳过更新
indexPredicate: "dateAdded > 2020-01-01", // postgres 支持,允许使用部分索引
},
)
/** 执行
* INSERT INTO user
* VALUES
* (externalId = abc123, firstName = Rizzrak, dateAdded = 2020-01-01),
* (externalId = cba321, firstName = Karzzir, dateAdded = 2022-01-01),
* ON CONFLICT (externalId) WHERE ( dateAdded > 2021-01-01 ) DO UPDATE
* SET firstName = EXCLUDED.firstName,
* SET dateAdded = EXCLUDED.dateAdded,
* WHERE user.firstName IS DISTINCT FROM EXCLUDED.firstName OR user.dateAdded IS DISTINCT FROM EXCLUDED.dateAdded
**/delete- 按实体 id、多个 id 或给定条件删除实体:
await repository.delete(1)
await repository.delete([1, 2, 3])
await repository.delete({ firstName: "Timber" })deleteAll- 删除目标类型的所有实体(不带 WHERE 子句)。
await repository.deleteAll()
// 执行 DELETE FROM user另请参阅 clear 方法,它执行的是数据库的 TRUNCATE TABLE 操作。
softDelete与restore- 按 id、多个 id、给定条件或条件对象数组软删除并恢复一行:
const repository = dataSource.getRepository(Entity)
// 软删除一个实体
await repository.softDelete(1)
// 你可以用 restore 恢复它;
await repository.restore(1)
// 软删除多个实体
await repository.softDelete([1, 2, 3])
// 或者按其他属性软删除
await repository.softDelete({ firstName: "Jake" })
// 条件对象数组会被 OR 组合成一条查询
await repository.softDelete([{ firstName: "Jake" }, { age: 25 }, { id: 42 }])
// 执行 UPDATE entity SET deletedAt = NOW() WHERE firstName = Jake OR age = 25 OR id = 42softRemove与recover- 这是softDelete和restore的替代方案。
// 你可以用 softRemove 软删除它们
const entities = await repository.find()
const entitiesAfterSoftRemove = await repository.softRemove(entities)
// 然后你可以用 recover 恢复它们;
await repository.recover(entitiesAfterSoftRemove)increment- 把匹配给定选项的实体的某个列增加指定值。
await repository.increment({ firstName: "Timber" }, "age", 3)decrement- 把匹配给定选项的某个列减少指定值。
await repository.decrement({ firstName: "Timber" }, "age", 3)exists- 检查是否存在匹配FindOptions的实体。
const exists = await repository.exists({
where: {
firstName: "Timber",
},
})existsBy- 检查是否存在匹配FindOptionsWhere的实体。
const exists = await repository.existsBy({ firstName: "Timber" })count- 统计匹配FindOptions的实体数量。对分页很有用。
const count = await repository.count({
where: {
firstName: "Timber",
},
})
const distinctCount = await repository.count({
select: {
firstName: true,
},
})提供了 select 时,统计的是所选列的不同组合数量;当与 relations 搭配时,也包含所选的关系列。如果未提供 select,默认计数行为不变。
countBy- 统计匹配FindOptionsWhere的实体数量。对分页很有用。
const count = await repository.countBy({ firstName: "Timber" })sum- 返回匹配FindOptionsWhere的所有实体某个数值字段的总和。
const sum = await repository.sum("age", { firstName: "Timber" })average- 返回匹配FindOptionsWhere的所有实体某个数值字段的平均值。
const average = await repository.average("age", { firstName: "Timber" })minimum- 返回匹配FindOptionsWhere的所有实体某个数值字段的最小值。
const minimum = await repository.minimum("age", { firstName: "Timber" })maximum- 返回匹配FindOptionsWhere的所有实体某个数值字段的最大值。
const maximum = await repository.maximum("age", { firstName: "Timber" })find- 查找匹配给定FindOptions的实体。
const timbers = await repository.find({
where: {
firstName: "Timber",
},
})findBy- 查找匹配给定FindWhereOptions的实体。
const timbers = await repository.findBy({
firstName: "Timber",
})findAndCount- 查找匹配给定FindOptions的实体。同时统计匹配给定条件的所有实体数量,但会忽略分页设置(from 和 take 选项)。
const [timbers, timbersCount] = await repository.findAndCount({
where: {
firstName: "Timber",
},
})findAndCountBy- 查找匹配给定FindOptionsWhere的实体。同时统计匹配给定条件的所有实体数量,但会忽略分页设置(from 和 take 选项)。
const [timbers, timbersCount] = await repository.findAndCountBy({
firstName: "Timber",
})findOne- 查找匹配给定FindOptions的第一个实体。
const timber = await repository.findOne({
where: {
firstName: "Timber",
},
})findOneBy- 查找匹配给定FindOptionsWhere的第一个实体。
const timber = await repository.findOneBy({ firstName: "Timber" })findOneOrFail- 查找匹配某个 id 或查找选项的第一个实体。如果没有匹配项,返回的 promise 会被拒绝。
const timber = await repository.findOneOrFail({
where: {
firstName: "Timber",
},
})findOneByOrFail- 查找匹配给定FindOptions的第一个实体。如果没有匹配项,返回的 promise 会被拒绝。
const timber = await repository.findOneByOrFail({ firstName: "Timber" })query- 执行一条原生 SQL 查询。
const rawData = await repository.query(`SELECT * FROM USERS`)
// 你也可以使用参数来避免 SQL 注入
// 不同驱动的语法有所不同
// aurora-mysql, better-sqlite3, capacitor, cordova,
// expo, mariadb, mysql, nativescript, react-native,
// sap, sqlite, sqljs
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = ? and age = ?",
["John", 24],
)
// aurora-postgres, cockroachdb, postgres
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = $1 and age = $2",
["John", 24],
)
// oracle
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = :1 and age = :2",
["John", 24],
)
// spanner
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = @param0 and age = @param1",
["John", 24],
)
// mssql
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = @0 and age = @1",
["John", 24],
)
// 当 extra.namedPlaceholders 为 true 时
// mysql2 还额外支持具名占位符
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = :name and age = :age",
{ name: "John", age: 24 },
)clear- 清空(截断)给定表中的所有数据。支持 cascade 选项,可同时清空带有指向该表外键的表中的所有数据(仅 PostgreSQL/CockroachDB 和 Oracle 支持;其他数据库在 cascade 选项设为 true 时会抛出错误)。
await repository.clear()
// 带 cascade 选项(仅 PostgreSQL/CockroachDB 和 Oracle)
await repository.clear({ cascade: true })额外选项
可以给 save 传入可选的 SaveOptions 参数。
data- 随持久化方法一起传递的额外数据。这些数据之后可以在订阅者中使用。listeners: boolean - 表示本次操作是否调用监听器和订阅者。默认是启用的,你可以在 save/remove 选项中设置{ listeners: false }来禁用它们。transaction: boolean - 默认情况下事务是启用的,持久化操作中的所有查询都会被包在事务里。你可以在持久化选项中设置{ transaction: false }来禁用这一行为。chunk: number - 把保存操作拆成多个分组块。例如,如果你想保存 100.000 个对象但遇到了问题,可以把它们拆成 10 组、每组 10.000 个对象(设置{ chunk: 10000 }),然后分别保存每一组。当你受限于底层驱动的参数数量上限而无法完成超大批量插入时,需要用到该选项。reload: boolean - 决定被持久化的实体是否应在持久化操作期间重新加载。它只在不支持 RETURNING / OUTPUT 语句的数据库上生效。默认启用。
示例:
userRepository.save(users, { chunk: 1000 })可以给 remove 和 delete 传入可选的 RemoveOptions 参数。
data- 随 remove 方法一起传递的额外数据。这些数据之后可以在订阅者中使用。listeners: boolean - 表示本次操作是否调用监听器和订阅者。默认是启用的,你可以在 save/remove 选项中设置{ listeners: false }来禁用它们。transaction: boolean - 默认情况下事务是启用的,持久化操作中的所有查询都会被包在事务里。你可以在持久化选项中设置{ transaction: false }来禁用这一行为。chunk: number - 把移除操作拆成多个分组块。例如,如果你想移除 100.000 个对象但遇到了问题,可以把它们拆成 10 组、每组 10.000 个对象(设置{ chunk: 10000 }),然后分别移除每一组。当你受限于底层驱动的参数数量上限而无法完成超大批量删除时,需要用到该选项。
示例:
userRepository.remove(users, { chunk: 1000 })TreeRepository API
关于 TreeRepository API,请参阅树形实体文档。
MongoRepository API
关于 MongoRepository API,请参阅 MongoDB 文档。
Repository API
manager- TheEntityManagerused by this repository.
const manager = repository.managermetadata- TheEntityMetadataof the entity managed by this repository.
const metadata = repository.metadataqueryRunner- The query runner used byEntityManager. Used only in transactional instances of EntityManager.
const queryRunner = repository.queryRunnertarget- The target entity class managed by this repository. Used only in transactional instances of EntityManager.
const target = repository.targetcreateQueryBuilder- Creates a query builder use to build SQL queries. Learn more about QueryBuilder.
const users = await repository
.createQueryBuilder("user")
.where("user.name = :name", { name: "John" })
.getMany()hasId- Checks if the given entity's primary column property is defined.
if (repository.hasId(user)) {
// ... do something
}getId- Gets the primary column property values of the given entity. If entity has composite primary keys then the returned value will be an object with names and values of primary columns.
const userId = repository.getId(user) // userId === 1create- Creates a new instance ofUser. Optionally accepts an object literal with user properties which will be written into newly created user object
const user = repository.create() // same as const user = new User();
const user = repository.create({
id: 1,
firstName: "Timber",
lastName: "Saw",
}) // same as const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";merge- Merges multiple entities into a single entity.
const user = new User()
repository.merge(user, { firstName: "Timber" }, { lastName: "Saw" }) // same as user.firstName = "Timber"; user.lastName = "Saw";preload- Creates a new entity from the given plain javascript object. If the entity already exists in the database, then it loads it (and everything related to it), replaces all values with the new ones from the given object, and returns the new entity. The new entity is actually an entity loaded from the database with all properties replaced from the new object.Note that given entity-like object must have an entity id / primary key to find entity by. Returns undefined if entity with given id was not found.
const partialUser = {
id: 1,
firstName: "Rizzrak",
profile: {
id: 1,
},
}
const user = await repository.preload(partialUser)
// user will contain all missing data from partialUser with partialUser property values:
// { id: 1, firstName: "Rizzrak", lastName: "Saw", profile: { id: 1, ... } }save- Saves a given entity or array of entities. If the entity already exist in the database, it is updated. If the entity does not exist in the database, it is inserted. It saves all given entities in a single transaction (in the case of entity, manager is not transactional). Also supports partial updating since all undefined properties are skipped. Returns the saved entity/entities.
await repository.save(user)
await repository.save([category1, category2, category3])remove- Removes a given entity or array of entities. It removes all given entities in a single transaction (in the case of entity, manager is not transactional). Returns the removed entity/entities.
await repository.remove(user)
await repository.remove([category1, category2, category3])insert- Inserts a new entity, or array of entities.
await repository.insert({
firstName: "Timber",
lastName: "Timber",
})
await repository.insert([
{
firstName: "Foo",
lastName: "Bar",
},
{
firstName: "Rizz",
lastName: "Rak",
},
])update- Updates entities by entity id, ids or given conditions. Sets fields from supplied partial entity.
await repository.update({ age: 18 }, { category: "ADULT" })
// executes UPDATE user SET category = ADULT WHERE age = 18
await repository.update(1, { firstName: "Rizzrak" })
// executes UPDATE user SET firstName = Rizzrak WHERE id = 1
// optionally request RETURNING / OUTPUT values (supported drivers only)
const result = await repository.update(
1,
{ firstName: "Rizzrak" },
{ returning: ["id", "firstName"] },
)
console.log(result.raw) // [{ id: 1, firstName: "Rizzrak" }]You can pass an array of condition objects to match multiple distinct sets of rows in a single call (conditions are OR'd together):
await repository.update([{ status: "expired" }, { flagged: true }], {
active: false,
})
// executes UPDATE user SET active = false WHERE status = 'expired' OR flagged = trueupdateAll- Updates all entities of target type (without WHERE clause). Sets fields from supplied partial entity.
await repository.updateAll({ category: "ADULT" })
// executes UPDATE user SET category = ADULT
await repository.updateAll(
{ category: "ADULT" },
{ returning: "*" }, // limited to drivers that support returning clauses
)upsert- Inserts a new entity or array of entities unless they already exist in which case they are updated instead. Supported by AuroraDataApi, Cockroach, Mysql, Postgres, and Sqlite database drivers.
When an upsert operation results in an update (due to a conflict), special columns like @UpdateDateColumn and @VersionColumn are automatically updated to their current values.
Columns marked with update: false or defined as computed generated columns (via asExpression/generatedType) are never included in the update set on conflict. If all non-conflict columns are excluded by these rules (i.e. there are no updatable columns), the upsert degrades to an insert-or-ignore operation and the existing row is left completely unchanged. On databases that support conflict targets (e.g. PostgreSQL, CockroachDB), this is scoped to the specified conflict columns; on MySQL-family databases, INSERT IGNORE is used which applies to all unique constraints.
await repository.upsert(
[
{ externalId: "abc123", firstName: "Rizzrak" },
{ externalId: "bca321", firstName: "Karzzir" },
],
["externalId"],
)
/** executes
* INSERT INTO user
* VALUES
* (externalId = abc123, firstName = Rizzrak),
* (externalId = cba321, firstName = Karzzir),
* ON CONFLICT (externalId) DO UPDATE
* SET firstName = EXCLUDED.firstName,
* updatedDate = CURRENT_TIMESTAMP,
* version = version + 1
**/You can also request values to be returned from an upsert (supported on drivers with RETURNING / OUTPUT support):
const { raw } = await repository.upsert(
{ externalId: "abc123", firstName: "Rizzrak" },
{
conflictPaths: ["externalId"],
returning: ["externalId", "firstName"],
},
)
console.log(raw) // [{ externalId: "abc123", firstName: "Rizzrak" }]await repository.upsert(
[
{ externalId: "abc123", firstName: "Rizzrak" },
{ externalId: "bca321", firstName: "Karzzir" },
],
{
conflictPaths: ["externalId"],
skipUpdateIfNoValuesChanged: true, // supported by postgres, skips update if it would not change row values
upsertType: "upsert", // "on-conflict-do-update" | "on-duplicate-key-update" | "upsert" - optionally provide an UpsertType - 'upsert' is currently only supported by CockroachDB
},
)
/** executes
* INSERT INTO user
* VALUES
* (externalId = abc123, firstName = Rizzrak),
* (externalId = cba321, firstName = Karzzir),
* ON CONFLICT (externalId) DO UPDATE
* SET firstName = EXCLUDED.firstName
* WHERE user.firstName IS DISTINCT FROM EXCLUDED.firstName
**/await repository.upsert(
[
{ externalId: "abc123", firstName: "Rizzrak", dateAdded: "2020-01-01" },
{ externalId: "bca321", firstName: "Karzzir", dateAdded: "2022-01-01" },
],
{
conflictPaths: ["externalId"],
skipUpdateIfNoValuesChanged: true, // supported by postgres, skips update if it would not change row values
indexPredicate: "dateAdded > 2020-01-01", // supported by postgres, allows for partial indexes
},
)
/** executes
* INSERT INTO user
* VALUES
* (externalId = abc123, firstName = Rizzrak, dateAdded = 2020-01-01),
* (externalId = cba321, firstName = Karzzir, dateAdded = 2022-01-01),
* ON CONFLICT (externalId) WHERE ( dateAdded > 2021-01-01 ) DO UPDATE
* SET firstName = EXCLUDED.firstName,
* SET dateAdded = EXCLUDED.dateAdded,
* WHERE user.firstName IS DISTINCT FROM EXCLUDED.firstName OR user.dateAdded IS DISTINCT FROM EXCLUDED.dateAdded
**/delete- Deletes entities by entity id, ids or given conditions:
await repository.delete(1)
await repository.delete([1, 2, 3])
await repository.delete({ firstName: "Timber" })deleteAll- Deletes all entities of target type (without WHERE clause).
await repository.deleteAll()
// executes DELETE FROM userRefer also to the clear method, which performs database TRUNCATE TABLE operation instead.
softDeleteandrestore- Soft deleting and restoring a row by id, ids, given conditions, or an array of condition objects:
const repository = dataSource.getRepository(Entity)
// Soft delete an entity
await repository.softDelete(1)
// And you can restore it using restore;
await repository.restore(1)
// Soft delete multiple entities
await repository.softDelete([1, 2, 3])
// Or soft delete by other attribute
await repository.softDelete({ firstName: "Jake" })
// An array of condition objects is OR'd into one query
await repository.softDelete([{ firstName: "Jake" }, { age: 25 }, { id: 42 }])
// executes UPDATE entity SET deletedAt = NOW() WHERE firstName = Jake OR age = 25 OR id = 42softRemoveandrecover- This is alternative tosoftDeleteandrestore.
// You can soft-delete them using softRemove
const entities = await repository.find()
const entitiesAfterSoftRemove = await repository.softRemove(entities)
// And You can recover them using recover;
await repository.recover(entitiesAfterSoftRemove)increment- Increments some column by provided value of entities that match given options.
await repository.increment({ firstName: "Timber" }, "age", 3)decrement- Decrements some column by provided value that match given options.
await repository.decrement({ firstName: "Timber" }, "age", 3)exists- Check whether any entity exists that matchesFindOptions.
const exists = await repository.exists({
where: {
firstName: "Timber",
},
})existsBy- Checks whether any entity exists that matchesFindOptionsWhere.
const exists = await repository.existsBy({ firstName: "Timber" })count- Counts entities that matchFindOptions. Useful for pagination.
const count = await repository.count({
where: {
firstName: "Timber",
},
})
const distinctCount = await repository.count({
select: {
firstName: true,
},
})When select is provided, counts distinct combinations of selected columns, including selected relation columns when paired with relations. If select is not provided, default count behavior is unchanged.
countBy- Counts entities that matchFindOptionsWhere. Useful for pagination.
const count = await repository.countBy({ firstName: "Timber" })sum- Returns the sum of a numeric field for all entities that matchFindOptionsWhere.
const sum = await repository.sum("age", { firstName: "Timber" })average- Returns the average of a numeric field for all entities that matchFindOptionsWhere.
const average = await repository.average("age", { firstName: "Timber" })minimum- Returns the minimum of a numeric field for all entities that matchFindOptionsWhere.
const minimum = await repository.minimum("age", { firstName: "Timber" })maximum- Returns the maximum of a numeric field for all entities that matchFindOptionsWhere.
const maximum = await repository.maximum("age", { firstName: "Timber" })find- Finds entities that match givenFindOptions.
const timbers = await repository.find({
where: {
firstName: "Timber",
},
})findBy- Finds entities that match givenFindWhereOptions.
const timbers = await repository.findBy({
firstName: "Timber",
})findAndCount- Finds entities that match givenFindOptions. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
const [timbers, timbersCount] = await repository.findAndCount({
where: {
firstName: "Timber",
},
})findAndCountBy- Finds entities that match givenFindOptionsWhere. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
const [timbers, timbersCount] = await repository.findAndCountBy({
firstName: "Timber",
})findOne- Finds the first entity that matches givenFindOptions.
const timber = await repository.findOne({
where: {
firstName: "Timber",
},
})findOneBy- Finds the first entity that matches givenFindOptionsWhere.
const timber = await repository.findOneBy({ firstName: "Timber" })findOneOrFail- Finds the first entity that matches some id or find options. Rejects the returned promise if nothing matches.
const timber = await repository.findOneOrFail({
where: {
firstName: "Timber",
},
})findOneByOrFail- Finds the first entity that matches givenFindOptions. Rejects the returned promise if nothing matches.
const timber = await repository.findOneByOrFail({ firstName: "Timber" })query- Executes a raw SQL query.
const rawData = await repository.query(`SELECT * FROM USERS`)
// You can also use parameters to avoid SQL injection
// The syntax differs between the drivers
// aurora-mysql, better-sqlite3, capacitor, cordova,
// expo, mariadb, mysql, nativescript, react-native,
// sap, sqlite, sqljs
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = ? and age = ?",
["John", 24],
)
// aurora-postgres, cockroachdb, postgres
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = $1 and age = $2",
["John", 24],
)
// oracle
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = :1 and age = :2",
["John", 24],
)
// spanner
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = @param0 and age = @param1",
["John", 24],
)
// mssql
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = @0 and age = @1",
["John", 24],
)
// mysql2 additionally supports named placeholders
// when extra.namedPlaceholders is true
const rawData = await repository.query(
"SELECT * FROM USERS WHERE name = :name and age = :age",
{ name: "John", age: 24 },
)clear- Clears all the data from (truncates) the given table. Supports cascade option to also clear all the data from the tables that have foreign keys to this table (supported by PostgreSQL/CockroachDB and Oracle only; other databases throw an error if cascade option is set to true).
await repository.clear()
// With cascade option (PostgreSQL/CockroachDB and Oracle only)
await repository.clear({ cascade: true })Additional Options
Optional SaveOptions can be passed as parameter for save.
data- Additional data to be passed with persist method. This data can be used in subscribers then.listeners: boolean - Indicates if listeners and subscribers are called for this operation. By default they are enabled, you can disable them by setting{ listeners: false }in save/remove options.transaction: boolean - By default transactions are enabled and all queries in persistence operation are wrapped into the transaction. You can disable this behaviour by setting{ transaction: false }in the persistence options.chunk: number - Breaks save execution into multiple groups of chunks. For example, if you want to save 100.000 objects but you have issues with saving them, you can break them into 10 groups of 10.000 objects (by setting{ chunk: 10000 }) and save each group separately. This option is needed to perform very big insertions when you have issues with underlying driver parameter number limitation.reload: boolean - Flag to determine whether the entity that is being persisted should be reloaded during the persistence operation. It will work only on databases which do not support RETURNING / OUTPUT statement. Enabled by default.
Example:
userRepository.save(users, { chunk: 1000 })Optional RemoveOptions can be passed as parameter for remove and delete.
data- Additional data to be passed with remove method. This data can be used in subscribers then.listeners: boolean - Indicates if listeners and subscribers are called for this operation. By default they are enabled, you can disable them by setting{ listeners: false }in save/remove options.transaction: boolean - By default transactions are enabled and all queries in persistence operation are wrapped into the transaction. You can disable this behaviour by setting{ transaction: false }in the persistence options.chunk: number - Breaks removal execution into multiple groups of chunks. For example, if you want to remove 100.000 objects but you have issues doing so, you can break them into 10 groups of 10.000 objects, by setting{ chunk: 10000 }, and remove each group separately. This option is needed to perform very big deletions when you have issues with underlying driver parameter number limitation.
Example:
userRepository.remove(users, { chunk: 1000 })TreeRepository API
For TreeRepository API refer to the Tree Entities documentation.
MongoRepository API
For MongoRepository API refer to the MongoDB documentation.