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

Prisma与MongoDB集成时无法执行查询的技术求助

Next.js + Prisma + MongoDB 连接失败:InvalidNamespace 错误

我在搭建新的Next.js项目时,尝试连接本地运行的MongoDB实例(MongoDB Compass可正常连接),但调用Prisma的findMany()时失败。

测试API端点代码(/src/pages/api/db-actions.ts)

import { db } from "@/lib/db";
import { NextApiRequest, NextApiResponse } from "next";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  console.log("Finding users...")
  const users = await db.user.findMany()
  
  console.log("Done", users)

  return res.status(200).json({users: users})
}

错误信息

⨯ PrismaClientKnownRequestError: 
Invalid `prisma.user.findMany()` invocation:

Raw query failed. Code: `unknown`. Message: `Kind: Command failed: Error code 73 (InvalidNamespace): Invalid namespace specified '.User', labels: {}`
    at In.handleRequestError (C:\dev\forenzix-migration-2\node_modules\@prisma\client\runtime\library.js:122:6854)
    at In.handleAndLogRequestError (C:\dev\forenzix-migration-2\node_modules\@prisma\client\runtime\library.js:122:6188)
    at In.request (C:\dev\forenzix-migration-2\node_modules\@prisma\client\runtime\library.js:122:5896)
    at async l (C:\dev\forenzix-migration-2\node_modules\@prisma\client\runtime\library.js:127:10871)
    at async handler (webpack-internal:///(api)/./src/pages/api/db-actions.ts:9:19)
    at async K (C:\dev\forenzix-migration-2\node_modules\next\dist\compiled\next-server\pages-api.runtime.dev.js:21:2946)
    at async U.render (C:\dev\forenzix-migration-2\node_modules\next\dist\compiled\next-server\pages-api.runtime.dev.js:21:3827)
    at async DevServer.runApi (C:\dev\forenzix-migration-2\node_modules\next\dist\server\next-server.js:556:9)
    at async NextNodeServer.handleCatchallRenderRequest (C:\dev\forenzix-migration-2\node_modules\next\dist\server\next-server.js:268:37)
    at async DevServer.handleRequestImpl (C:\dev\forenzix-migration-2\node_modules\next\dist\server\base-server.js:807:17)
    at async C:\dev\forenzix-migration-2\node_modules\next\dist\server\dev\next-dev-server.js:331:20)
    at async Span.traceAsyncFn (C:\dev\forenzix-migration-2\node_modules\next\dist\trace\trace.js:151:20)
    at async DevServer.handleRequest (C:\dev\forenzix-migration-2\node_modules\next\dist\server\dev\next-dev-server.js:328:24)
    at async invokeRender (C:\dev\forenzix-migration-2\node_modules\next\dist\server\lib\router-server.js:163:21)
    at async handleRequest (C:\dev\forenzix-migration-2\node_modules\next\dist\server\lib\router-server.js:342:24) {
  code: 'P2010',
  clientVersion: '5.11.0',
  meta: {
    modelName: 'User',
    code: 'unknown',
    message: "Kind: Command failed: Error code 73 (InvalidNamespace): Invalid namespace specified '.User', labels: {}"
  },
  page: '/api/db-actions'
}

相关配置

Prisma Schema(/prisma/schema.prisma)

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

model User {
  id          String @id @default(auto()) @map("_id") @db.ObjectId
  name        String @unique    // Added by me
  passhash    String            // Added by me
}

.env 文件

DATABASE_URL=mongodb://localhost:27017/test

环境版本

  • Node: v18.18.8
  • Next.js: 14.1.0
  • Prisma (& Client): 5.11.0
  • MongoDB: 7.0.6

我已经在MongoDB Compass的test数据库下创建了User集合,但问题依然存在。尝试了多种方法都没解决,求帮助。


解决方案

  1. 修正集合名称匹配问题:MongoDB集合名称区分大小写,Prisma默认会将模型名转为小写复数形式(比如User模型对应users集合)。你手动创建的是User集合,导致Prisma找不到对应命名空间。

    • 解决方式二选一:
      • 将MongoDB中的集合重命名为users
      • 在Prisma模型中指定集合名:
        model User {
          id          String @id @default(auto()) @map("_id") @db.ObjectId
          name        String @unique
          passhash    String
          @@map("User") // 强制指定集合名为User
        }
        
  2. 重新生成Prisma Client:修改schema后必须执行以下命令更新客户端:

    npx prisma generate
    
  3. 验证连接字符串:确保DATABASE_URL无多余空格或符号,可尝试替换localhost为127.0.0.1,即mongodb://127.0.0.1:27017/test。

  4. 重新同步数据库结构:如果手动修改过schema,重新拉取并生成客户端:

    npx prisma db pull
    npx prisma generate
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 11:45:03