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

Prisma提示Order模型不存在问题求助

问题:Prisma新增Order模型后仍报错“Property 'order' does not exist on type 'PrismaClient<PrismaClientOptions, never, DefaultArgs>'”

使用Prisma开发在线商城时,已在schema.prisma中新增Order模型,但始终触发上述类型错误。尝试过关闭VSCode、重启电脑、执行npx prisma generate和npx prisma db push,均无法解决问题。

schema.prisma代码

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

generator client {
  provider        = "prisma-client-js"
  output = "../../node_modules/.prisma/client"
}

model Order {
  id                String @id @default(auto()) @map("_id") @db.ObjectId
  userId            String @db.ObjectId
  amount            Float
  currency          String
  status            String
  deliverStatus     String?
  createdData       DateTime? @default(now())
  paymentIntentId   String @unique
  products          CartProductType[]
  address           Address?
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model Account {
  id                 String @id @default(auto()) @map("_id") @db.ObjectId
  userId             String @db.ObjectId
  type               String
  provider           String
  providerAccountId  String
  refresh_token      String?  @db.String
  access_token       String?  @db.String
  expires_at         Int?
  token_type         String?
  scope              String?
  id_token           String?  @db.String
  session_state      String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

model User {
  id            String @id @default(auto()) @map("_id") @db.ObjectId
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  hashedPassword String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  role Role @default(USER)
  accounts      Account[]
  orders     Order[]
}


type CartProductType{
  id          String
  name        String
  description String
  category    String
  brand       String
  selectedImg Image
  quantity    Int
  price       Int
}

type Image {
  color       String
  colorCode   String
  image       String
}

type Address{
  city        String
  country     String
  line1       String
  line2       String?
  postal_code String
  state       String
}

enum Role{
    USER
    ADMIN
}

接口代码

import Stripe from "stripe";
import prisma from "@/libs/prismadb";
import { NextResponse } from "next/server";
import { CartProductType } from "@/app/product/[productId]/ProductDetails";
import { getCurrentUser } from "@/actions/getCurrentUser";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string);

const calculateOrderAmount = (items: CartProductType[]) => {
  const totalPrice = items.reduce((acc, item) => {
    const itemTotal = item.price * item.quantity;
    return acc + itemTotal;
  }, 0);

  return totalPrice;
};

export async function POST(request: Request) {
  const currentUser = await getCurrentUser();

  if (!currentUser) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await request.json();
  const { items, payment_intent_id } = body;
  const total = calculateOrderAmount(items) * 100;
  const orderData = {
    user: { connect: { id: currentUser.id } },
    amount: total,
    currency: "usd",
    status: "pending",
    deliveryStatus: "pending",
    paymentIntentId: payment_intent_id,
    products: items,
  };

  if (payment_intent_id) {
    const current_intent = await stripe.paymentIntents.retrieve(
      payment_intent_id
    );
    if (current_intent) {
      const updated_intent = await stripe.paymentIntents.update(
        payment_intent_id,
        { amount: total }
      );
      //update the intent
      const [existing_order, update_order] = await Promise.all([
prisma.order.findFirst({
          where: { paymentIntentId: payment_intent_id },
        }),
        prisma.order.update({
          where: { paymentIntentId: payment_intent_id },
          data: {
            amount: total,
            products: items,
          },
        }),
      ]);
      if (!existing_order) {
        return NextResponse.json(
          { error: "Invalid Payment Intent" },
          { status: 400 }
        );
      }
      return NextResponse.json({ paymentIntent: updated_intent });
    }
  } else {
    //create the intent
    const paymentIntent = await stripe.paymentIntents.create({
      amount: total,
      currency: "usd",
      automatic_payment_methods: { enabled: true },
    });
    //create the order
    orderData.paymentIntentId = paymentIntent.id;

    await prisma.order.create({
      data: orderData,
    });
    return NextResponse.json({ paymentIntent });
  }
}
解决方案
  1. 强制重新生成Prisma Client
    执行以下命令覆盖旧的Client文件,避免缓存导致模型更新不生效:

    npx prisma generate --force
    
  2. 检查Client生成路径匹配度
    schema中配置了output = "../../node_modules/.prisma/client",确认项目目录结构是否和该路径一致。如果路径错误,生成的Client文件无法被代码识别,可临时注释该配置使用默认路径后重新生成。

  3. 重启TypeScript服务
    在VSCode中按Ctrl+Shift+P(Windows)或Cmd+Shift+P(Mac)打开命令面板,执行"TypeScript: Restart TS Server",清除类型缓存。

  4. 验证Prisma Client导入正确性
    检查@/libs/prismadb中的实例是否正确从@prisma/client导入,确保没有引用本地旧文件。示例正确导入方式:

    import { PrismaClient } from '@prisma/client'
    
    const prisma = new PrismaClient()
    export default prisma
    
  5. 清理依赖重装
    若以上方法无效,删除node_modules、package-lock.json后执行:

    npm install
    npx prisma generate
    

额外注意:schema中Order模型的字段为deliverStatus(缺少字母y),但接口代码中使用deliveryStatus,会导致订单创建时字段不匹配,建议同步修改为一致命名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:10:57