DBCollectionFree class abstract
An abstract class representing a MongoDB collection with utility methods. The DBCollectionFree class provides an abstraction over a MongoDB collection, offering various methods to interact with the database, such as checking for the existence of a document by its ID, updating fields, form validation, and generating REST API routes. This class is meant to be extended by other classes for more specific collection implementations. Features include:
- Document CRUD operations (Create, Read, Update, Delete)
- Form validation using DBFormFree
- Index management
- Event handling for database operations
- Automatic REST API route generation
- Search and filter capabilities
- Pagination support
Constructors
-
DBCollectionFree({required String name, required Db db, required DBFormFree form, Map<
String, DBIndex> indexes = const {}}) - Constructor to initialize the collection with required parameters. Creates a new database collection instance and automatically handles:
Properties
- collection → DbCollection
-
Provides direct access to the underlying MongoDB collection.
The collection is retrieved using the
db.collection(name)method.no setter - collectionEvent ↔ CollectionEvent
-
Event handlers for collection operations (insert, update, delete).
getter/setter pair
- db ↔ Db
-
The MongoDB database instance.
getter/setter pair
- form ↔ DBFormFree
-
The form definition containing field validators and structure.
getter/setter pair
- hashCode → int
-
The hash code for this object.
no setterinherited
-
indexes
↔ Map<
String, DBIndex> -
Map of database indexes to be created for this collection.
getter/setter pair
- name ↔ String
-
The name of the MongoDB collection.
getter/setter pair
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
copy(
String id) → Future< void> -
Creates a copy of a document by its ID and inserts it as a new document.
This method retrieves an existing document, removes its
_idfield, and inserts it as a new document with a newly generated ObjectId. Triggers CollectionEvent.onInsert if the copy operation is successful. Parameters: -
createIndex(
{String? key, Map< String, dynamic> ? keys, bool? unique, bool? sparse, bool? background, bool? dropDups, Map<String, dynamic> ? partialFilterExpression, String? name, bool? modernReply, Map? collation}) → Future<Map< String, dynamic> > - Creates a database index on the collection. This method creates a new index on the MongoDB collection with the specified options. Indexes improve query performance and can enforce uniqueness constraints. Parameters:
-
delete(
String id) → Future< bool> - Deletes a document from the collection by its ID. This method validates the ID format and attempts to delete the corresponding document. Triggers CollectionEvent.onDelete if successful. Parameters:
-
deleteOid(
ObjectId oid) → Future< bool> - Deletes a document from the collection by its ObjectId. This method performs the actual deletion using the MongoDB ObjectId directly. It retrieves the document before deletion to trigger the CollectionEvent.onDelete event with the deleted document data. Parameters:
-
existId(
String idField) → Future< bool> -
Checks if a document with the given ID exists in the collection.
This method validates the ID format and checks for document existence.
The
idFieldshould be a valid MongoDB ObjectId string representation. Parameters: -
existOid(
ObjectId? id) → Future< bool> - Checks if a document with the given ObjectId exists in the collection. This method performs the actual existence check using the MongoDB ObjectId directly, providing better performance than string-based checks. Parameters:
-
getAll(
{SelectorBuilder? selector, Map< String, Object?> ? filter, FindOptions? findOptions, String? hint, int? skip, Map<String, Object> ? sort, int? limit, Map<String, Object> ? hintDocument, Map<String, Object> ? projection, Map<String, Object> ? rawOptions}) → Future<List< Map< >String, Object?> > - Retrieves multiple documents from the collection with flexible options. This method provides comprehensive querying capabilities including filtering, sorting, pagination, and field projection. The results are automatically processed through the form validation system. Parameters:
-
getById(
String id) → Future< Map< String, Object?> ?> - Retrieves a single document by its ID. This method converts the string ID to an ObjectId and delegates to getByOid for the actual retrieval. The returned document is processed through form validation. Parameters:
-
getByOid(
ObjectId? oid) → Future< Map< String, Object?> ?> - Retrieves a single document by its ObjectId. This method performs the actual document retrieval using the MongoDB ObjectId directly. The returned document is processed through the form validation system to ensure proper data formatting. Parameters:
-
getCount(
{String? field, Object? value, Map< String, Object?> ? filter}) → Future<int> - Gets the count of documents in the collection. This method returns the total number of documents matching the specified criteria. If no criteria are provided, it returns the total count of all documents in the collection. Parameters:
-
getSearchableFilter(
{required Map< String, Object?> inputs, String searchFiled = 'search'}) → Map<String, Object?> - Generates search and filter criteria based on form field definitions. This method creates MongoDB query filters based on:
-
insert(
Map< String, Object?> data) → Future<FormResultFree> - Inserts a new document into the collection. This method validates the data before insertion and triggers the CollectionEvent.onInsert event if the insertion is successful. Parameters:
-
mergeOne(
String id, Map< String, Object?> data) → Future<FormResultFree?> - Merges new data with an existing document by its ID. This method performs a partial update by merging the provided data with the existing document. Only the specified fields are validated and updated, while other fields remain unchanged. Triggers CollectionEvent.onUpdate if successful. Parameters:
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
replaceOne(
String id, Map< String, Object?> data) → Future<FormResultFree?> - Replaces an entire document by its ID. This method completely replaces the existing document with new data, after validating the new data. The document must exist for the operation to succeed. Triggers CollectionEvent.onUpdate if successful. Parameters:
-
routeDeleteOne(
String path, {List< String> methods = const [Methods.GET], Future<ApiDoc> ? apiDoc()?, AuthController? auth, List<String> extraPath = const [], List<String> excludePaths = const [], List<String> hosts = const ['*'], Map<String, Object?> params = const {}, List<String> permissions = const [], List<int> ports = const []}) → FinchRoute - Creates a route for deleting documents from the collection. This method generates a REST API endpoint that handles document deletion by ID. The route expects a document ID in the URL path and processes GET requests to delete the specified document. The delete operation:
-
routeGetAll(
String path, {List< String> methods = const [Methods.GET], Future<ApiDoc> ? apiDoc()?, AuthController? auth, List<String> extraPath = const [], List<String> excludePaths = const [], List<String> hosts = const ['*'], Map<String, Object?> params = const {}, List<String> permissions = const [], List<int> ports = const [], List<FinchRoute> children = const [], bool paging = true, int pageSize = 20, bool orderReverse = true, String orderBy = '_id'}) → FinchRoute - Creates a route for retrieving all documents in the collection. This method generates a REST API endpoint that handles listing all documents in the collection with support for:
-
routeGetOne(
String path, {List< String> methods = const [Methods.GET], Future<ApiDoc> ? apiDoc()?, AuthController? auth, List<String> extraPath = const [], List<String> excludePaths = const [], List<String> hosts = const ['*'], Map<String, Object?> params = const {}, List<String> permissions = const [], List<int> ports = const []}) → FinchRoute - Creates a route for retrieving a single document by its ID. This method generates a REST API endpoint that handles fetching individual documents from the collection. The route expects a document ID in the URL path and processes GET requests to return the specified document. The retrieval operation:
-
routeInsert(
String path, {List< String> methods = const [Methods.POST], Future<ApiDoc> ? apiDoc()?, AuthController? auth, List<String> extraPath = const [], List<String> excludePaths = const [], List<String> hosts = const ['*'], Map<String, Object?> params = const {}, List<String> permissions = const [], List<int> ports = const []}) → FinchRoute - Creates a route for inserting new documents into the collection. This method generates a REST API endpoint that handles document creation with automatic form validation. The route processes POST requests containing document data, validates it against the form definition, and inserts it into the collection. Parameters:
-
routes(
String path, {bool useRouteAll = true, bool useRouteDelete = true, bool useRouteInsert = true, bool useRouteUpdate = true, bool useRouteGetOne = true, bool paging = true, int pageSize = 20, bool orderReverse = true, String orderBy = '_id', Future< ApiDoc> ? docAll()?, Future<ApiDoc> ? docDelete()?, Future<ApiDoc> ? docInsert()?, Future<ApiDoc> ? docUpdate()?, Future<ApiDoc> ? docOne()?, List<FinchRoute> children = const []}) → List<FinchRoute> - Generates a complete set of REST API routes for this collection. This method creates standard CRUD (Create, Read, Update, Delete) routes for the collection, providing a full REST API interface. Each route type can be individually enabled or disabled. Generated routes:
-
routeUpdate(
String path, {List< String> methods = const [Methods.POST], Future<ApiDoc> ? apiDoc()?, AuthController? auth, List<String> extraPath = const [], List<String> excludePaths = const [], List<String> hosts = const ['*'], Map<String, Object?> params = const {}, List<String> permissions = const [], List<int> ports = const []}) → FinchRoute - Creates a route for updating existing documents in the collection. This method generates a REST API endpoint that handles document updates via complete replacement. The route expects a document ID in the URL path and processes POST requests containing the new document data. The update operation:
-
toFormResult(
Map< String, Object?> document) → Future<FormResultFree> - Converts a raw MongoDB document to a FormResultFree object. This method processes a document through the form validation system and returns the complete validation result, which includes both the processed data and any validation information. Parameters:
-
toModel(
Map< String, Object?> document, {List<String> ? selectedFields}) → Future<Map< String, Object?> > - Converts a raw MongoDB document to a validated model. This method processes a document through the form validation system to ensure proper data types and formatting. Optionally filters the result to include only selected fields. Parameters:
-
toString(
) → String -
A string representation of this object.
inherited
-
updateField(
String id, String field, Object? value) → Future< FormResultFree?> - Updates a specific field of a document by its ID. This method validates the new field value using the form definition before updating the document. Only the specified field is validated and updated. Triggers CollectionEvent.onUpdate if successful. Parameters:
-
validate(
Map< String, Object?> data, {List<String> onlyCheckKeys = const []}) → Future<FormResultFree> - Validates data against the form definition. Performs comprehensive validation of input data based on the validators defined in the collection's form. This method can validate all fields or only specific fields if specified. Parameters:
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
printDesign(
) → void - Prints the design and structure of all registered collections. This static method provides a comprehensive overview of all collection instances, including their fields, counts, events, and indexes. The output is displayed as JSON format using Console.json. This is useful for debugging and understanding the database schema during development.