findById is a method that retrieves a single record by ID. It loads data with the specified subset and throws a NotFoundException if the record doesnβt exist.
findById is not defined in BaseModelClass. Itβs a standard pattern automatically generated
by the Syncer in each Model class when you create an Entity.Type Signature
Auto-Generated Code
Sonamu automatically generates the following code based on your Entity:- Calls
findManyto query by ID - Fetches only one record with
num: 1, page: 1 - Throws
NotFoundExceptionif no result - Returns the first record
Parameters
subset
Specifies the subset of data to retrieve. Type:SubsetKey (e.g., "A", "B", "C")
Subsets determine the shape of data as defined in your Entity configuration. Each subset can include different fields and relationships.
id
The ID of the record to retrieve. Type:number
Return Value
Type:Promise<SubsetMapping[T]>
Returns a record of the specified subset type. The type is automatically inferred based on the subset.
Exceptions
NotFoundException
ThrowsNotFoundException if the record with the given ID doesnβt exist.
Basic Usage
Simple Query
Usage in API
findById is automatically exposed as a REST API with the @api decorator:
Usage by Subset
Subset A (Basic)
Subset B (With Relationships)
Subset C (Nested Relationships)
Practical Examples
- User Profile
- Order Details
- Permission Check
- Error Handling
findById vs findOne vs findMany
findById
- Fetches single record by ID
- Throws exception if record not found
- Simplest and fastest
- Auto-generated
findOne
- Fetches single record by conditions
- Returns null if record not found
- Supports complex conditions
- Must be implemented manually (optional)
findMany
- Fetches multiple records by conditions
- Supports pagination
- Returns total count
- Auto-generated
Type Safety
Return types are automatically inferred based on the subset:Client Usage
React (TanStack Query)
Vue
Cautions
1. Subset Selection
Choose subsets that include only the necessary data. Loading unnecessary relationships degrades performance.2. Exception Handling
findById throws an exception if the record doesnβt exist. Add exception handling when necessary.
3. Null Possibility
If record existence is uncertain, usefindOne (requires manual implementation).
Next Steps
findMany
List queries and pagination
save
Save and update records
Subset
Understanding subsets
Exception Handling
Handling NotFoundException