Prisma查询MongoDB时添加orderBy后where子句失效求助
Prisma + MongoDB: orderBy 导致 where 筛选条件失效的解决方案
问题根源
在使用Prisma的relationMode="prisma"时,嵌套的NOT + responses.some条件结合orderBy可能触发Prisma查询生成的bug,导致MongoDB无法正确解析筛选逻辑,最终忽略where条件。
解决方案
方案1:升级Prisma到最新稳定版
旧版本Prisma对MongoDB的关联查询+排序支持存在缺陷,先尝试升级修复:
npm update prisma @prisma/client npx prisma generate
方案2:改用反向查询(推荐)
先获取用户已回答的问题ID集合,再通过id.notIn筛选未回答的问题,绕过嵌套关联的bug:
// 第一步:获取当前用户所有已回答的问题ID const answeredQuestionIds = await prisma.response.findMany({ where: { userId }, select: { questionId: true }, // 只取需要的字段,提升性能 }); const ids = answeredQuestionIds.map(item => item.questionId); // 第二步:筛选未回答的问题并排序 const unansweredQuestions = await prisma.question.findMany({ orderBy: { entryDate: 'desc' }, where: { id: { notIn: ids }, }, skip, take, });
方案3:使用MongoDB原生查询
如果上述方案仍不生效,直接用Prisma的原生命令执行MongoDB查询:
const unansweredQuestions = await prisma.$runCommandRaw({ find: "Question", // 集合名遵循Prisma默认复数规则 filter: { _id: { $nin: await prisma.response.findMany({ where: { userId }, select: { questionId: true }, }).then(res => res.map(item => item.questionId)) } }, sort: { entryDate: -1 }, // -1对应降序 skip: skip, limit: take });
性能优化建议
- 给
Response模型的userId和questionId建立复合索引:
在Prisma Schema中添加:model Response { // ... 其他字段 userId String @db.ObjectId questionId String @db.ObjectId @@index([userId, questionId]) } - 给
Question模型的entryDate建立索引:model Question { // ... 其他字段 entryDate DateTime @@index([entryDate]) }
添加索引后执行npx prisma db push生效。
内容的提问来源于stack exchange,提问作者6nagi9
相关产品推荐
相关产品推荐

