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

如何在NestJS中为Prisma查询添加自定义条件

实现方案

Prisma查询构建器不支持在where子句中直接嵌入异步逻辑(比如调用Google API的异步验证),所以需要拆分步骤完成:

1. 基础查询+后过滤(适合数据量小的场景)

先获取满足基础条件(比如userId)的Job数据,再用异步函数过滤符合location要求的条目:

第一步:查询基础数据

// 查询包含location字段的基础结果
const rawJobs = await this.prisma.job.findMany({
  skip,
  take: limit,
  where: { userId },
  select: {
    name: true,
    status: true,
    date: true,
    category: true,
    id: true,
    jobOffers: true,
    location: true, // 必须包含该字段用于后续验证
  },
});

第二步:异步过滤

// 定义异步验证函数,调用Google API检查坐标
async function validateLocation(job) {
  // 替换为你的Google API调用逻辑
  const locationValid = await callGoogleGeoAPI(job.location);
  return locationValid;
}

// 过滤出符合条件的Job
const jobs = await Promise.all(
  rawJobs.map(async job => {
    const isValid = await validateLocation(job);
    return isValid ? job : null;
  })
).then(results => results.filter(Boolean)); // 移除无效条目

2. 预验证ID再查询(适合分页或大数据量场景)

如果需要严格保证分页的准确性(避免过滤后数据不足limit条),可以先验证所有符合基础条件的Job的location,拿到有效ID列表后再查询最终数据:

第一步:获取所有目标Job的ID和Location

const allUserJobs = await this.prisma.job.findMany({
  where: { userId },
  select: { id: true, location: true },
});

第二步:验证Location并收集有效ID

const validJobIds = await Promise.all(
  allUserJobs.map(async job => {
    const isValid = await validateLocation(job);
    return isValid ? job.id : null;
  })
).then(ids => ids.filter(Boolean));

第三步:查询最终分页数据

const jobs = await this.prisma.job.findMany({
  where: { id: { in: validJobIds } },
  skip,
  take: limit,
  select: {
    name: true,
    status: true,
    date: true,
    category: true,
    id: true,
    jobOffers: true,
  },
});

注意点

  • 第一种方案实现简单,但如果过滤后有效数据不足limit,分页会出现数据缺失的情况。
  • 第二种方案能保证分页准确性,但如果用户的Job数量极大,需要考虑分批验证或优化API调用效率,避免请求过多导致的性能问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:15:09