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

Prisma查询License时获取嵌套User的email及TS类型错误解决

解决方案

1. 修正TypeScript错误根源

你的map回调中,当license.product?.user.email不存在时没有返回值,导致数组混入undefined,与声明的返回类型不匹配。需要确保每个迭代都返回有效数据,或过滤掉无效条目。

2. 调整查询逻辑,去除不必要字段

直接在findMany的select中指定需要的字段,避免获取productId和多余关联数据:

import { Prisma, License } from '@prisma/client'
import { prisma } from './context'

// 定义返回类型:剔除productId,新增email字段
type LicenseWithEmail = Omit<License, 'productId'> & { email: string }

export const getLicenses = async (): Promise<LicenseWithEmail[] | null> => {
  const licenses = await prisma.license.findMany({
    orderBy: { createdAt: 'desc' },
    select: {
      id: true,
      name: true,
      total: true,
      used: true,
      createdAt: true,
      // 仅嵌套获取所需的email字段
      product: {
        select: {
          user: { select: { email: true } }
        }
      }
    }
  })

  // 映射并过滤无有效email的条目
  const result = licenses
    .map(license => {
      const email = license.product?.user.email
      if (email) {
        // 解构剔除product字段,添加email
        const { product, ...rest } = license
        return { ...rest, email }
      }
      return null
    })
    // 过滤null值,确保数组全为有效数据
    .filter(Boolean) as LicenseWithEmail[]

  return result.length > 0 ? result : null
}

export const db = { getLicenses }

3. 适配GraphQL Schema(可选)

如果你的GraphQL License类型已包含email字段且不含productId,当前返回结构可直接匹配。若未更新类型,需同步调整schema.ts中的License类型定义,保证字段一致。

关键说明

  • 用Omit<License, 'productId'>从原License类型中移除productId,再添加email字段,定义精准的返回类型。
  • 通过select而非include精准获取所需字段,减少数据库查询开销,同时避免冗余数据。
  • 借助filter(Boolean)过滤无有效email的条目,确保返回数组无null或undefined,匹配类型声明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:19:01