字
字节笔记本
2026年5月3日
TanStack Start - 数据库集成 (Databases)
API中转
¥120
在 TanStack Start 应用中集成和使用数据库。由于服务端函数只是在服务端执行的函数,你可以像在任何其他服务端项目中一样使用数据库。
官方数据库合作伙伴
- Neon ⭐ - 无服务器 PostgreSQL,自动扩展、分支功能
- Convex ⭐ - 全栈应用平台,实时同步、内置认证
数据库对比
| 数据库 | 类型 | 优势 | 适用场景 |
|---|---|---|---|
| Neon | Serverless PostgreSQL | 自动扩展、分支功能 | 需要快速迭代的项目 |
| Convex | 全栈平台 | 实时同步、内置认证 | 实时应用 |
| Prisma | ORM | 类型安全、易用 | TypeScript 项目 |
| Drizzle | ORM | 轻量级、零依赖 | 包大小敏感 |
| Supabase | BaaS | 功能全面、开源 | 快速原型开发 |
| Turso | Edge SQLite | 边缘部署、低延迟 | 全球分布应用 |
Neon 快速开始
bash
npm install @neondatabase/serverlesstsx
// utils/db.ts
import { neon } from '@neondatabase/serverless'
const sql = neon(process.env.VITE_DATABASE_URL!)
export { sql }
// routes/posts.tsx
export const getPostsFn = createServerFn({ method: 'GET' }).handler(async () => {
return await sql`SELECT * FROM posts ORDER BY created_at DESC`
})Convex 快速开始
bash
npm install convex
npx convex devtsx
// convex/schema.ts
export default defineSchema({
posts: defineTable({
title: v.string(),
content: v.string(),
authorId: v.string(),
}).index('by_author', ['authorId']),
})
// convex/posts.ts
export const list = query({
handler: async (ctx) => await ctx.db.query('posts').collect(),
})Prisma 快速开始
bash
npm install prisma @prisma/client
npx prisma initprisma
// prisma/schema.prisma
model Post {
id String @id @default(cuid())
title String
content String?
author User @relation(fields: [authorId], references: [id])
authorId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}tsx
export const getPostsFn = createServerFn({ method: 'GET' }).handler(async () => {
return await prisma.post.findMany({
include: { author: true },
orderBy: { createdAt: 'desc' },
})
})Drizzle 快速开始
tsx
// db/schema.ts
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
content: text('content'),
createdAt: timestamp('created_at').defaultNow().notNull(),
})
// server/posts.ts
export const getPostsFn = createServerFn({ method: 'GET' }).handler(async () => {
return await db.select().from(posts).orderBy(desc(posts.createdAt))
})选择建议
| 需求 | 推荐 |
|---|---|
| 快速启动 | Convex |
| PostgreSQL | Neon |
| 类型安全 | Prisma |
| 轻量级 | Drizzle |
| 实时应用 | Convex / Supabase |
| 边缘部署 | Turso |
分享: