---
lang: en
title: 'API docs: repository'
keywords: LoopBack 4.0, LoopBack 4, Node.js, TypeScript, OpenAPI
sidebar: lb4_sidebar
editurl: https://github.com/loopbackio/loopback-next/tree/master/packages/repository
permalink: /doc/en/lb4/apidocs.repository.html
---

<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [@loopback/repository](./repository.md)

## repository package

A common set of interfaces for interacting with databases.

This module provides data access facilities to various databases and services as well as the constructs for modeling and accessing those data.

## Classes

|  Class | Description |
|  --- | --- |
|  [AnyType](./repository.anytype.md) | Any type |
|  [ArrayType](./repository.arraytype.md) | Array type, such as string\[\] |
|  [BooleanType](./repository.booleantype.md) | Boolean type |
|  [BufferType](./repository.buffertype.md) | Buffer (binary) type |
|  [CrudRepositoryImpl](./repository.crudrepositoryimpl.md) | Repository implementation |
|  [DateType](./repository.datetype.md) | Date type |
|  [DefaultBelongsToRepository](./repository.defaultbelongstorepository.md) |  |
|  [DefaultCrudRepository](./repository.defaultcrudrepository.md) | Default implementation of CRUD repository using legacy juggler model and data source |
|  [DefaultHasManyRepository](./repository.defaulthasmanyrepository.md) |  |
|  [DefaultHasManyThroughRepository](./repository.defaulthasmanythroughrepository.md) | a class for CRUD operations for hasManyThrough relation.<!-- -->Warning: The hasManyThrough interface is experimental and is subject to change. If backwards-incompatible changes are made, a new major version may not be released. |
|  [DefaultHasOneRepository](./repository.defaulthasonerepository.md) |  |
|  [DefaultKeyValueRepository](./repository.defaultkeyvaluerepository.md) | An implementation of KeyValueRepository based on loopback-datasource-juggler |
|  [DefaultReferencesManyRepository](./repository.defaultreferencesmanyrepository.md) |  |
|  [DefaultTransactionalRepository](./repository.defaulttransactionalrepository.md) | Default implementation of CRUD repository using legacy juggler model and data source with beginTransaction() method for connectors which support Transactions |
|  [Entity](./repository.entity.md) | Base class for entities which have unique ids |
|  [EntityNotFoundError](./repository.entitynotfounderror.md) |  |
|  [Event](./repository.event.md) | Domain events |
|  [InvalidPolymorphismError](./repository.invalidpolymorphismerror.md) |  |
|  [InvalidRelationError](./repository.invalidrelationerror.md) |  |
|  [Model](./repository.model.md) | Base class for models |
|  [ModelDefinition](./repository.modeldefinition.md) | Definition for a model |
|  [ModelMetadataHelper](./repository.modelmetadatahelper.md) |  |
|  [ModelType](./repository.modeltype.md) | Model type |
|  [NullType](./repository.nulltype.md) | Null type |
|  [NumberType](./repository.numbertype.md) | Number type |
|  [ObjectType](./repository.objecttype.md) | Object type |
|  [RepositoryMetadata](./repository.repositorymetadata.md) | Metadata for a repository |
|  [RepositoryMixinDoc](./repository.repositorymixindoc.md) | A dummy class created to generate the tsdoc for the members in repository mixin. Please don't use it.<!-- -->The members are implemented in function <a href="#RepositoryMixin">RepositoryMixin</a> |
|  [StringType](./repository.stringtype.md) | String type |
|  [UnionType](./repository.uniontype.md) | Union type, such as string \| number |
|  [ValueObject](./repository.valueobject.md) | Base class for value objects - An object that contains attributes but has no conceptual identity. They should be treated as immutable. |

## Enumerations

|  Enumeration | Description |
|  --- | --- |
|  [IsolationLevel](./repository.isolationlevel.md) | Isolation level |
|  [RelationType](./repository.relationtype.md) |  |

## Functions

|  Function | Description |
|  --- | --- |
|  [belongsTo(targetResolver, definition, propertyDefinition)](./repository.belongsto.md) | Decorator for belongsTo |
|  [bindModel(modelClass, ds)](./repository.bindmodel.md) | This is a bridge to the legacy DAO class. The function mixes DAO methods into a model class and attach it to a given data source |
|  [buildLookupMap(list, keyName, reducer)](./repository.buildlookupmap.md) | Returns a map which maps key values(ids) to instances. The instances can be grouped by different strategies. |
|  [buildModelDefinition(target, def)](./repository.buildmodeldefinition.md) | Build model definition from decorations |
|  [constrainDataObject(originalData, constraint)](./repository.constraindataobject.md) | A utility function which takes a model instance data and enforces constraint(s) on it |
|  [constrainDataObjects(originalData, constraint)](./repository.constraindataobjects.md) | A utility function which takes an array of model instance data and enforces constraint(s) on it |
|  [constrainFilter(originalFilter, constraint)](./repository.constrainfilter.md) | A utility function which takes a filter and enforces constraint(s) on it |
|  [constrainWhere(originalWhere, constraint)](./repository.constrainwhere.md) | A utility function which takes a where filter and enforces constraint(s) on it |
|  [constrainWhereOr(originalWhere, constraint)](./repository.constrainwhereor.md) | A utility function which takes a where filter and enforces constraint(s) on it with OR clause |
|  [createBelongsToAccessor(belongsToMetadata, targetRepositoryGetter, sourceRepository)](./repository.createbelongstoaccessor.md) | Enforces a BelongsTo constraint on a repository If the target model is polymorphic, i.e. stored within different repositories, supply the targetRepositoryGetter with a dictionary in the form of {<!-- -->\[typeName: string\]: repositoryGetter<!-- -->} |
|  [createBelongsToInclusionResolver(meta, getTargetRepoDict)](./repository.createbelongstoinclusionresolver.md) | Creates InclusionResolver for BelongsTo relation. Notice that this function only generates the inclusionResolver. It doesn't register it for the source repository.<!-- -->Notice: scope field for inclusion is not supported yet |
|  [createHasManyInclusionResolver(meta, getTargetRepo)](./repository.createhasmanyinclusionresolver.md) | Creates InclusionResolver for HasMany relation. Notice that this function only generates the inclusionResolver. It doesn't register it for the source repository.<!-- -->Notice: scope field for inclusion is not supported yet. |
|  [createHasManyRepositoryFactory(relationMetadata, targetRepositoryGetter)](./repository.createhasmanyrepositoryfactory.md) | Enforces a constraint on a repository based on a relationship contract between models. For example, if a Customer model is related to an Order model via a HasMany relation, then, the relational repository returned by the factory function would be constrained by a Customer model instance's id(s). |
|  [createHasManyThroughRepositoryFactory(relationMetadata, targetRepositoryGetter, throughRepositoryGetter)](./repository.createhasmanythroughrepositoryfactory.md) |  |
|  [createHasOneRepositoryFactory(relationMetadata, targetRepositoryGetter)](./repository.createhasonerepositoryfactory.md) | Enforces a constraint on a repository based on a relationship contract between models. For example, if a Customer model is related to an Address model via a HasOne relation, then, the relational repository returned by the factory function would be constrained by a Customer model instance's id(s).<!-- -->If the target model is polymorphic, i.e. stored within different repositories, supply the targetRepositoryGetter with a dictionary in the form of {<!-- -->\[typeName: string\]: repositoryGetter<!-- -->} |
|  [createModelClassBinding(modelClass)](./repository.createmodelclassbinding.md) | Create a binding for the given model class |
|  [createReferencesManyAccessor(referencesManyMetadata, targetRepoGetter, sourceRepository)](./repository.createreferencesmanyaccessor.md) | Enforces a ReferencesMany constraint on a repository |
|  [createReferencesManyInclusionResolver(meta, getTargetRepo)](./repository.createreferencesmanyinclusionresolver.md) | Creates InclusionResolver for ReferencesMany relation. Notice that this function only generates the inclusionResolver. It doesn't register it for the source repository.<!-- -->Notice: scope field for inclusion is not supported yet |
|  [deduplicate(input)](./repository.deduplicate.md) | Dedupe an array |
|  [defineCrudRepositoryClass(entityClass)](./repository.definecrudrepositoryclass.md) | Create (define) an entity CRUD repository class for the given model. This function always uses <code>DefaultCrudRepository</code> as the base class, use <code>defineRepositoryClass</code> if you want to use your own base repository. |
|  [defineKeyValueRepositoryClass(modelClass)](./repository.definekeyvaluerepositoryclass.md) | Create (define) a KeyValue repository class for the given entity. This function always uses <code>DefaultKeyValueRepository</code> as the base class, use <code>defineRepositoryClass</code> if you want to use your own base repository. |
|  [defineModelClass(base, definition)](./repository.definemodelclass.md) | Create (define) a new model class with the given name and definition. |
|  [defineRepositoryClass(modelClass, baseRepositoryClass)](./repository.definerepositoryclass.md) | Create (define) a repository class for the given model.<!-- -->See also <code>defineCrudRepositoryClass</code> and <code>defineKeyValueRepositoryClass</code> for convenience wrappers providing repository class factory for the default CRUD and KeyValue implementations.<!-- -->\*\*❗️IMPORTANT: The compiler (TypeScript 3.8) is not able to correctly infer generic arguments <code>M</code> and <code>R</code> from the class constructors provided in function arguments. You must always provide both M and R types explicitly.\*\* |
|  [embedsMany(definition)](./repository.embedsmany.md) | Decorator for embedsMany |
|  [embedsOne(definition)](./repository.embedsone.md) | Decorator for embedsOne |
|  [ensurePromise(p)](./repository.ensurepromise.md) | Ensure the value is a promise |
|  [findByForeignKeys(targetRepository, fkName, fkValues, scope, options)](./repository.findbyforeignkeys.md) | Finds model instances that contain any of the provided foreign key values. |
|  [flattenMapByKeys(sourceIds, targetMap)](./repository.flattenmapbykeys.md) | Returns an array of instances from the target map. The order of arrays is based on the order of sourceIds |
|  [flattenTargetsOfOneToManyRelation(sourceIds, targetEntities, targetKey)](./repository.flattentargetsofonetomanyrelation.md) | Returns an array of instances. The order of arrays is based on as a result of one to many relation. The order of arrays is based on the order of sourceIds |
|  [flattenTargetsOfOneToOneRelation(sourceIds, targetEntities, targetKey)](./repository.flattentargetsofonetoonerelation.md) | Returns an array of instances. The order of arrays is based on the order of sourceIds |
|  [getKeyValue(model, keyName)](./repository.getkeyvalue.md) | Returns value of a keyName. Aims to resolve ObjectId problem of Mongo. |
|  [getModelRelations(modelCtor)](./repository.getmodelrelations.md) | Get metadata of all relations defined on a given model class. |
|  [hasMany(targetResolver, definition)](./repository.hasmany.md) | Decorator for hasMany Calls property.array decorator underneath the hood and infers foreign key name from target model name unless explicitly specified |
|  [hasOne(targetResolver, definition)](./repository.hasone.md) |  |
|  [includeFieldIfNot(fields, fieldToInclude)](./repository.includefieldifnot.md) |  |
|  [includeRelatedModels(targetRepository, entities, include, options)](./repository.includerelatedmodels.md) | Returns model instances that include related models that have a registered resolver. |
|  [isBsonType(value)](./repository.isbsontype.md) | Checks if the value is BsonType (mongodb) It uses a general way to check the type ,so that it can detect different versions of bson that might be used in the code base. Might need to update in the future. |
|  [isBuiltinType(fn)](./repository.isbuiltintype.md) | Check if the provided function is a built-in type provided by JavaScript and/or Node.js. E.g. <code>Number</code>, <code>Array</code>, <code>Buffer</code>, etc. |
|  [isEntityNotFoundError(e)](./repository.isentitynotfounderror.md) |  |
|  [isInvalidPolymorphismError(e)](./repository.isinvalidpolymorphismerror.md) |  |
|  [isInvalidRelationError(e)](./repository.isinvalidrelationerror.md) |  |
|  [isTypeResolver(fn)](./repository.istyperesolver.md) | A function that checks whether a function is a TypeResolver or not. |
|  [model(definition)](./repository.model.md) | Decorator for model definitions |
|  [normalizeKey(rawKey)](./repository.normalizekey.md) | Workaround for MongoDB, where the connector returns ObjectID values even for properties configured with "type: string". |
|  [Null()](./repository.null.md) | A boxed type for <code>null</code> |
|  [property(definition)](./repository.property.md) | Decorator for model properties |
|  [reduceAsArray(acc, it)](./repository.reduceasarray.md) | Returns an array of instances. For HasMany relation usage. |
|  [reduceAsSingleItem(\_acc, it)](./repository.reduceassingleitem.md) | Returns a single of an instance. For HasOne and BelongsTo relation usage. |
|  [referencesMany(targetResolver, definition, propertyDefinition)](./repository.referencesmany.md) | Decorator for referencesMany |
|  [referencesOne(definition)](./repository.referencesone.md) | Decorator for referencesOne |
|  [rejectNavigationalPropertiesInData(modelClass, data)](./repository.rejectnavigationalpropertiesindata.md) | Check model data for navigational properties linking to related models. Throw a descriptive error if any such property is found. |
|  [relation(definition)](./repository.relation.md) | Decorator for relations |
|  [repository(repositoryName)](./repository.repository.md) | Decorator for repository injections on properties or method arguments |
|  [repository(model, dataSource)](./repository.repository_1.md) | Decorator for DefaultCrudRepository generation and injection on properties or method arguments based on the given model and dataSource (or their names) |
|  [RepositoryMixin(superClass)](./repository.repositorymixin.md) | A mixin class for Application that creates a .repository() function to register a repository automatically. Also overrides component function to allow it to register repositories automatically. |
|  [resolveType(fn)](./repository.resolvetype.md) | Resolve a type value that may have been provided via TypeResolver. |
|  [resolveType(fn)](./repository.resolvetype_1.md) |  |

## Interfaces

|  Interface | Description |
|  --- | --- |
|  [AnyObject](./repository.anyobject.md) | Objects with open properties |
|  [ApplicationWithRepositories](./repository.applicationwithrepositories.md) | Interface for an Application mixed in with RepositoryMixin |
|  [BaseRepositoryClass](./repository.baserepositoryclass.md) | Signature for repository classes that can be used as the base class for <code>define*</code> functions. The constructor of a base repository class accepts the target model constructor and the datasource to use.<code>define*</code> functions require a class implementing this interface on input. |
|  [BelongsToAccessor](./repository.belongstoaccessor.md) |  |
|  [BelongsToDefinition](./repository.belongstodefinition.md) |  |
|  [BelongsToRepository](./repository.belongstorepository.md) | CRUD operations for a target repository of a BelongsTo relation |
|  [Class](./repository.class.md) | Interface for classes with <code>new</code> operator and static properties/methods |
|  [Connector](./repository.connector.md) | Common properties/operations for connectors |
|  [ConstructorFunction](./repository.constructorfunction.md) | Interface for constructor functions without <code>new</code> operator. |
|  [Count](./repository.count.md) | Count of Model instances that were successful for methods like <code>updateAll</code>, <code>deleteAll</code>, etc. |
|  [CrudConnector](./repository.crudconnector.md) | CRUD operations for connector implementations |
|  [CrudRepository](./repository.crudrepository.md) | Basic CRUD operations for ValueObject and Entity. No ID is required. |
|  [DataSource](./repository.datasource.md) | DataSource denotes a configured connector |
|  [EntityCrudRepository](./repository.entitycrudrepository.md) | CRUD operations for a repository of entities |
|  [EntityRepository](./repository.entityrepository.md) | Base interface for a repository of entities |
|  [ExecutableRepository](./repository.executablerepository.md) |  |
|  [HasManyDefinition](./repository.hasmanydefinition.md) | HasManyDefinition defines one-to-many relations and also possible defines many-to-many relations with through models. |
|  [HasManyRepository](./repository.hasmanyrepository.md) | CRUD operations for a target repository of a HasMany relation |
|  [HasManyRepositoryFactory](./repository.hasmanyrepositoryfactory.md) |  |
|  [HasManyThroughRepository](./repository.hasmanythroughrepository.md) | CRUD operations for a target repository of a HasManyThrough relation<!-- -->EXPERIMENTAL: This interface is not stable and may change in the near future. Backwards-incompatible changes may be introduced in semver-minor versions. |
|  [HasOneDefinition](./repository.hasonedefinition.md) |  |
|  [HasOneRepository](./repository.hasonerepository.md) | CRUD operations for a target repository of a HasMany relation |
|  [HasOneRepositoryFactory](./repository.hasonerepositoryfactory.md) |  |
|  [JsonSchemaWithExtensions](./repository.jsonschemawithextensions.md) | This module defines the key classes representing building blocks for Domain Driven Design. See https://en.wikipedia.org/wiki/Domain-driven\_design\#Building\_blocks |
|  [KeyValueRepository](./repository.keyvaluerepository.md) | Key/Value operations for connector implementations |
|  [KVConnector](./repository.kvconnector.md) | Key/Value operations for connector implementations |
|  [ModelDefinitionSyntax](./repository.modeldefinitionsyntax.md) | DSL for building a model definition. |
|  [ModelRepositoryClass](./repository.modelrepositoryclass.md) | Signature for a Repository class bound to a given model. The constructor accepts only the dataSource to use for persistence.<code>define*</code> functions return a class implementing this interface. |
|  [ModelSettings](./repository.modelsettings.md) | Defining the settings for a model See https://loopback.io/doc/en/lb4/Model.html\#supported-entries-of-model-definition |
|  [Persistable](./repository.persistable.md) |  |
|  [PropertyDefinition](./repository.propertydefinition.md) | Property definition for a model |
|  [PropertyForm](./repository.propertyform.md) | See https://github.com/loopbackio/loopback-datasource-juggler/issues/432 |
|  [ReferencesManyAccessor](./repository.referencesmanyaccessor.md) |  |
|  [ReferencesManyDefinition](./repository.referencesmanydefinition.md) |  |
|  [ReferencesManyRepository](./repository.referencesmanyrepository.md) | CRUD operations for a target repository of a ReferencesMany relation |
|  [RelationDefinitionBase](./repository.relationdefinitionbase.md) |  |
|  [Repository](./repository.repository.md) |  |
|  [RepositoryComponent](./repository.repositorycomponent.md) | This interface describes additional Component properties allowing components to contribute Repository-related artifacts. |
|  [SchemaMigrationOptions](./repository.schemamigrationoptions.md) |  |
|  [Transaction](./repository.transaction.md) | Local transaction |
|  [TransactionalRepository](./repository.transactionalrepository.md) | Repository Interface for Repositories that support Transactions |
|  [Type](./repository.type.md) |  |

## Namespaces

|  Namespace | Description |
|  --- | --- |
|  [ConnectorInterfaces](./repository.connectorinterfaces.md) | Interfaces adopted by a [Connector](./repository.connector.md)<!-- -->. |
|  [juggler](./repository.juggler.md) |  |
|  [property](./repository.property.md) |  |
|  [repository](./repository.repository.md) |  |
|  [RepositoryBindings](./repository.repositorybindings.md) | Binding keys and namespaces for repository related bindings |
|  [RepositoryTags](./repository.repositorytags.md) | Binding tags for repository related bindings |

## Variables

|  Variable | Description |
|  --- | --- |
|  [ANY](./repository.any.md) |  |
|  [BOOLEAN](./repository.boolean.md) |  |
|  [BUFFER](./repository.buffer.md) |  |
|  [CountSchema](./repository.countschema.md) | JSON Schema describing the Count interface. It's the response type for REST calls to APIs which return <code>count</code>. The type is compatible with <code>SchemaObject</code> from <code>@loopback/openapi-v3</code>, which is not an explicit dependency for <code>@loopback/repository</code>. |
|  [DATE](./repository.date.md) |  |
|  [MODEL\_KEY](./repository.model_key.md) |  |
|  [MODEL\_PROPERTIES\_KEY](./repository.model_properties_key.md) |  |
|  [MODEL\_WITH\_PROPERTIES\_KEY](./repository.model_with_properties_key.md) |  |
|  [NULL](./repository.null.md) |  |
|  [NUMBER](./repository.number.md) |  |
|  [RELATIONS\_KEY](./repository.relations_key.md) |  |
|  [STRING](./repository.string.md) |  |

## Type Aliases

|  Type Alias | Description |
|  --- | --- |
|  [Callback](./repository.callback.md) | Type alias for Node.js callback functions |
|  [Command](./repository.command.md) | Type for a command |
|  [Constructor](./repository.constructor.md) | Constructor type - class or function |
|  [DataObject](./repository.dataobject.md) | Type alias for strongly or weakly typed objects of T |
|  [DeepPartial](./repository.deeppartial.md) | An extension of the built-in Partial<T> type which allows partial values in deeply nested properties too. |
|  [DynamicModelCtor](./repository.dynamicmodelctor.md) | A type describing a model class created via <code>defineModelClass</code>.<!-- -->Assuming template arguments <code>BaseCtor</code> and <code>Props</code>, this type describes a class constructor with the following properties: - a constructor function accepting <code>DataObject&lt;Props&gt;</code> as the only argument, this argument is optional - all static fields (properties, methods) from <code>BaseCtor</code> are inherited and available as static fields on the dynamic class - all prototype fields from <code>BaseCtor</code> prototype are inherited and available as prototype fields on the dynamic class |
|  [EntityData](./repository.entitydata.md) |  |
|  [EntityResolver](./repository.entityresolver.md) |  |
|  [HasManyThroughRepositoryFactory](./repository.hasmanythroughrepositoryfactory.md) | a factory to generate hasManyThrough repository class.<!-- -->Warning: The hasManyThrough interface is experimental and is subject to change. If backwards-incompatible changes are made, a new major version may not be released. |
|  [InclusionResolver](./repository.inclusionresolver.md) |  |
|  [KeyValueFilter](./repository.keyvaluefilter.md) | Filter for keys |
|  [NamedParameters](./repository.namedparameters.md) | Named parameters, such as <code>{x: 1, y: 'a'}</code> |
|  [Options](./repository.options.md) | Type alias for Node.js options object |
|  [PositionalParameters](./repository.positionalparameters.md) | Positional parameters, such as \[1, 'a'\] |
|  [PropertyMap](./repository.propertymap.md) |  |
|  [PropertyType](./repository.propertytype.md) |  |
|  [PrototypeOf](./repository.prototypeof.md) | Type helper to infer prototype from a constructor function.<!-- -->Example: <code>PrototypeOf&lt;typeof Entity&gt;</code> is resolved to <code>Entity</code>. |
|  [RelationDefinitionMap](./repository.relationdefinitionmap.md) | A key-value map describing model relations. A relation name is used as the key, a relation definition is the value. |
|  [RelationMetadata](./repository.relationmetadata.md) | A union type describing all possible Relation metadata objects. |
|  [RepositoryDecorator](./repository.repositorydecorator.md) | Type definition for decorators returned by <code>@repository</code> decorator factory |
|  [StringKeyOf](./repository.stringkeyof.md) |  |
|  [TransactionalEntityRepository](./repository.transactionalentityrepository.md) | A type for CRUD repositories that are backed by IDs and support Transactions |
|  [TypeResolver](./repository.typeresolver.md) | A type resolver is a function that returns a class representing the type, typically a Model or Entity (e.g. Product).<!-- -->We use type resolvers to break require() loops when defining relations. The target model (class) is provided via a provider, thus deferring the actual reference to the class itself until later, when both sides of the relation are created as JavaScript classes. |


