Find By ID Tutorial
Retrieving an entity by its unique identifier is a common operation in any database system. With Onyx Database, you can efficiently retrieve entities using the findById
method. This tutorial demonstrates how to use findById
to retrieve an entity.
Steps to Retrieve an Entity by ID (Onyx Cloud Database)
1
Invoke the findById Method
Use the
findById
method to retrieve the entity by its unique identifier.1// Basic lookup by primary key
2const season = await db.findById(Season, 2015);
3
4// Optionally hydrate resolver-backed fields when they exist
5const seasonWithStats = await db.findById(Season, 2015, {
6 resolvers: ['teamStats'],
7});
- The
findById
method expects the identifier of the entity you are looking for. - If the entity does not exist,
findById
returnsnull
. - To fetch resolver-backed attributes, pass an options object as the third argument with a
resolvers
array (for example,db.findById(Season, 2015, { resolvers: ["teamStats"] })
). This is optional—leave it out for entities without resolvers.
2
Confirm the Entity Was Retrieved
Check if the returned entity is not null and use it as needed.
1if (season != null) {
2 console.log(`The season has ${season.conferences.size} conferences!`);
3}
Important Notes
- The
findById
method is optimized for retrieving entities by their primary keys. - If you need to retrieve an entity based on other attributes, consider using the
find
orquery
methods.
Troubleshooting
- Entity Not Found: Ensure that the identifier you are using exists in the database.
- Incorrect Identifier Type: Verify that the identifier's data type matches the type defined in your entity's primary key.
- Null Pointer Exceptions: Always check if the returned entity is
null
before accessing its properties.
Next Steps
Now that you know how to retrieve an entity by its unique identifier, you can explore more advanced querying techniques: