Exercise 2: Replacing a Post's Tags — Possible Solution ========================================================= import { prisma } from "./lib/prisma"; export async function setPostTags(slug: string, tagNames: string[]) { const names = [...new Set(tagNames.map((n) => n.trim().toLowerCase()))] .filter((n) => n.length > 0); return prisma.post.update({ where: { slug }, data: { tags: { set: [], // 1. remove all current links connectOrCreate: names.map((name) => ({ // 2. link or create each tag where: { name }, create: { name }, })), }, }, include: { tags: true }, }); } How it works: - set: [] disconnects every tag currently linked to the post. The tag records themselves are not deleted — other posts may use them. - connectOrCreate then links each requested tag, creating any that don't exist yet. - Prisma runs the whole nested write as one transaction, so the post never ends up with no tags part-way through. - The names are trimmed, lower-cased and de-duplicated first, so "Prisma", " prisma" and "prisma" don't create three separate tags or fail on the unique name. Example: await setPostTags("tagging-posts", ["Prisma", "orm", "prisma"]); // tags are now: prisma, orm WHY THIS WORKS AS AN ANSWER ------------------------------ It uses set to clear and connectOrCreate to rebuild in a single atomic call, and cleans the input so real-world messy tag lists don't cause duplicates or unique-constraint errors.