Drizzle ORM中findMany使用问题及Supabase环境报错排查
解决Drizzle ORM + Supabase环境下findMany触发TypeError的问题
错误根源
Cannot read properties of undefined (reading 'findMany') 本质是你调用findMany的对象为undefined,核心原因是对Drizzle ORM的API使用方式混淆,或是配置环节遗漏。
排查与修正步骤
1. 确认Drizzle版本与依赖
findMany属于Drizzle Relations API,需要drizzle-orm版本≥v0.28.0,同时确保已安装drizzle-orm和@supabase/supabase-js依赖:
npm install drizzle-orm @supabase/supabase-js
2. 检查DB实例初始化配置
必须将schema与relations一同传入drizzle初始化函数,否则db.query下不会生成带关系查询能力的模型对象:
// @modules/restaurant/db.ts import { createClient } from '@supabase/supabase-js'; import { drizzle } from 'drizzle-orm/supabase-js'; import { restaurants } from './schema'; import { restaurantRelations } from './relation'; const supabase = createClient( process.env.SUPABASE_URL!, process.env.SUPABASE_ANON_KEY! ); // 关键:schema需包含表定义和对应的relations export const db = drizzle(supabase, { schema: { restaurants, restaurantRelations }, });
3. 正确调用findMany方法
findMany是query API的方法,必须通过db.query.[表名]调用,而非直接在表schema对象上调用:
正确用法
// /api/restaurant的GET请求处理逻辑 import { db } from '@modules/restaurant/db'; export async function getRestaurants() { // 通过db.query.[表名]调用findMany,支持关联查询 const restaurants = await db.query.restaurants.findMany({ with: { // 若定义了关联,可按需加载关联数据 category: true } }); return restaurants; }
错误用法(直接触发undefined)
// 错误:db.restaurants是表schema对象,无findMany方法 const restaurants = await db.restaurants.findMany();
4. 验证relations定义有效性
确保relation.ts中正确定义了表的关联关系,且与schema对应:
// relation.ts import { relations } from 'drizzle-orm'; import { restaurants } from './schema'; import { categories } from './categories'; export const restaurantRelations = relations(restaurants, ({ one }) => ({ category: one(categories, { fields: [restaurants.categoryId], references: [categories.id] }) }));
关键区别
db.select().from(restaurants):基础查询API,无需relations配置即可使用db.query.restaurants.findMany():Relations API,必须依赖正确的relations配置和db.query调用路径
内容的提问来源于stack exchange,提问作者Chi Hao
相关产品推荐
相关产品推荐

