To keep our main code clean and organised, we’ll use a separate file for handling record retrieval and query execution with Prisma. This will ensure our index.html remains clutter-free and help maintain a clean project structure.
Step 1: Setting Up a New find.ts File
In this file, we’ll focus on different find-related operations using Prisma's powerful querying methods. Let’s start by creating find.ts and exploring how to retrieve records using Prisma’s find methods.
Example Code in find.ts
import { PrismaClient } from '@prisma/client';
// Initialize Prisma Client
const prisma = new PrismaClient();
const main = async () => {
// Method 1: Find all posts
const getAllFromDB = await prisma.post.findMany();
console.log("All posts:", getAllFromDB);
// Method 2: Find the first post with a specific criterion
const findFirstPost = await prisma.post.findFirst({
where: {
id: 1
}
});
console.log("First post:", findFirstPost);
};
main();
Explanation of Methods
findMany: Retrieves all posts in the database.
findFirst: Retrieves the first record that matches a specified criterion. Here, we are fetching the first post with an id of 1.
Custom Search Criteria
You can search by fields like title, content, or authorName instead of id. Prisma will return the first record that matches the criteria, making it flexible for various search operations.
Using findFirstOrThrow for Error Handling
Prisma provides findFirstOrThrow to handle cases where no records match the criteria. It automatically throws an error if no records are found, so there’s no need to manually handle errors.
Update your code as follows:
import { PrismaClient } from '@prisma/client';
// Initialize Prisma Client
const prisma = new PrismaClient();
const main = async () => {
// Find all posts
const getAllFromDB = await prisma.post.findMany();
console.log("All posts:", getAllFromDB);
// Find the first post with specific criteria or throw an error if not found
const findFirstPost = await prisma.post.findFirstOrThrow({
where: {
id: 1
}
});
console.log("First post:", findFirstPost);
};
main();
Using findUnique and findUniqueOrThrow
Prisma’s findUnique is a method designed specifically for unique fields, like id in the Post model. Unlike findFirst, which retrieves the first record matching a criterion, findUnique will search only using unique fields.
Here’s how to use findUnique and findUniqueOrThrow:
import { PrismaClient } from '@prisma/client';
// Initialize Prisma Client
const prisma = new PrismaClient();
const main = async () => {
// Find all posts
const getAllFromDB = await prisma.post.findMany();
console.log("All posts:", getAllFromDB);
// Find first post with criteria or throw error
const findFirstPost = await prisma.post.findFirstOrThrow({
where: {
id: 1
}
});
console.log("First post:", findFirstPost);
// Find unique post with criteria
const findUniquePost = await prisma.post.findUnique({
where: {
id: 1
}
});
console.log("Unique post:", findUniquePost);
// Find unique post or throw error if not found
const findUniquePostOrThrow = await prisma.post.findUniqueOrThrow({
where: {
id: 1
}
});
console.log("Unique post with throw:", findUniquePostOrThrow);
};
main();
Important Note on findUnique and findUniqueOrThrow
In Prisma, findUnique and findUniqueOrThrow can only be used with columns that are unique, like id. Non-unique columns, such as title, content, or authorName, cannot be used with findUnique since these fields may have duplicate values across records. Using findUniqueOrThrow will throw an error if the record is not found, providing built-in error handling.
Summary of Find Methods
We’ve covered five essential methods to find records in Prisma:
findMany - Retrieves all records that match the criteria.
findFirst - Finds the first record that matches the criteria.
findUnique - Retrieves a record based on a unique field.
findFirstOrThrow - Retrieves the first record or throws an error if none are found.
findUniqueOrThrow - Finds a unique record or throws an error if it doesn’t exist.
Using these methods, you can efficiently search and retrieve records from your database while handling errors gracefully.
With these find operations, you now have a powerful toolkit for querying your data using Prisma. These methods ensure your code remains clean, efficient, and type-safe. Let me know if you have further questions or want to explore Prisma’s update and delete operations next!