You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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} />
    </>
  );
}

可能的解决方法

  1. 修正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;
      }
      
  2. 禁用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',
      });
      
  3. 重新生成Prisma客户端

    • 修改Prisma模型后,必须重新生成客户端才能让关联查询生效。执行以下命令:
      npx prisma generate
      
    • 重启Next.js开发服务器,确保新的客户端被加载。
  4. 验证API路由的返回数据

    • 在API路由中添加console.log(maintenanceItems),确认服务端确实返回了包含property字段的数据。如果服务端日志里没有property,说明Prisma查询有问题,需要检查模型关联是否正确,或尝试重新运行npx prisma db push确保数据库结构与模型一致。
  5. 检查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);
      

内容的提问来源于stack exchange,提问作者Gavin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:37:50