Next.js中Prisma查询MongoDB关联字段property返回undefined问题
问题:Next.js中Prisma关联查询返回的
property字段为undefined/null,但Postman正常 我通过Prisma查询MongoDB数据库,期望关联返回property数据。Postman调用接口时能正确返回包含property的结果,但在Next.js应用中该字段却显示为undefined或null。
相关代码片段
API路由查询代码
export async function GET(request: NextRequest) { const maintenanceItems = await prisma.maintenance.findMany({ include: { property: true, } }) return NextResponse.json(maintenanceItems) }
前端调用接口代码
let maintenanceItems: NewMaintenanceIncidentType[] = []; export const getMaintenanceItems = async () => { try { const response = await fetch(`${process.env.BASE_URL}/api/maintenance/`, { method: "GET", headers: { "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error("Failed to fetch Maintenance Items"); } maintenanceItems = await response.json(); console.log("from the server: ", maintenanceItems); } catch (error) { console.log("Server fetch failed on OpenMaintenanceItemPage ", error); } return maintenanceItems };
Prisma模型定义
model Maintenance { id String @id @default(auto()) @map("_id") @db.ObjectId name String description String status String image String? createdDate DateTime @default(now()) dueDate DateTime property Property @relation(fields: [propertyId], references: [id]) propertyId String @db.ObjectId } model Property { id String @id @default(auto()) @map("_id") @db.ObjectId propertyType String streetNumber String street String postcode String apartmentNumber String? city String county String propertyCategory String status String maintenanceTasks Maintenance[] userProperties UserProperty[] }
TypeScript类型定义
export type NewMaintenanceIncidentType = { id: string, name: string, description: string, status: string, image: string, createdDate: Date, dueDate: Date, property: PropertyType, reportedBy: string, assignedTo: string, propertyId: string, } export type PropertyType = { id: string; propertyType: string; streetNumber: string; street: string; postcode: string; apartmentNumber: string; city: string; county: string; propertyCategory: string; status: string; }
服务端页面调用
export default async function OpenMaintenanceItemsPage() { const openMaintenanceItems = await getMaintenanceItems(); return ( <> <Typography>Open Maintenance Items Page</Typography> <BasicTable openMaintenanceItems={openMaintenanceItems} /> </> ); }
可能的解决方法
修正TypeScript类型定义不匹配问题
- 你的
NewMaintenanceIncidentType中image是必填string,但Prisma模型里image是可选String?;同时reportedBy和assignedTo在Prisma模型中不存在,这些不匹配可能导致TypeScript类型断言异常,甚至影响数据解析。 - 另外
PropertyType中的apartmentNumber是必填string,但模型里是可选String?,建议调整类型定义与Prisma模型一致:export type NewMaintenanceIncidentType = { id: string; name: string; description: string; status: string; image?: string; createdDate: string; dueDate: string; property: PropertyType; propertyId: string; } export type PropertyType = { id: string; propertyType: string; streetNumber: string; street: string; postcode: string; apartmentNumber?: string; city: string; county: string; propertyCategory: string; status: string; }
- 你的
禁用Next.js fetch缓存
- 服务端组件的fetch默认会缓存数据,可能导致你拿到旧的未包含
property的缓存结果。在fetch请求中添加cache: 'no-store'禁用缓存:const response = await fetch(`${process.env.BASE_URL}/api/maintenance/`, { method: "GET", headers: { "Content-Type": "application/json", }, cache: 'no-store', });
- 服务端组件的fetch默认会缓存数据,可能导致你拿到旧的未包含
重新生成Prisma客户端
- 修改Prisma模型后,必须重新生成客户端才能让关联查询生效。执行以下命令:
npx prisma generate - 重启Next.js开发服务器,确保新的客户端被加载。
- 修改Prisma模型后,必须重新生成客户端才能让关联查询生效。执行以下命令:
验证API路由的返回数据
- 在API路由中添加
console.log(maintenanceItems),确认服务端确实返回了包含property字段的数据。如果服务端日志里没有property,说明Prisma查询有问题,需要检查模型关联是否正确,或尝试重新运行npx prisma db push确保数据库结构与模型一致。
- 在API路由中添加
检查JSON序列化问题
- MongoDB的
ObjectId和DateTime类型在JSON序列化时可能存在格式问题,虽然不应该导致字段丢失,但可以尝试在API路由中手动处理数据,确保property被正确序列化:const maintenanceItems = await prisma.maintenance.findMany({ include: { property: true, } }); const serializedItems = maintenanceItems.map(item => ({ ...item, createdDate: item.createdDate.toISOString(), dueDate: item.dueDate.toISOString(), property: { ...item.property, apartmentNumber: item.property.apartmentNumber || undefined, } })); return NextResponse.json(serializedItems);
- MongoDB的
内容的提问来源于stack exchange,提问作者Gavin
相关产品推荐
相关产品推荐

