在Prisma+MongoDB+Next.js中创建多层嵌套数组失败求助
问题:商品规格关联多颜色数组创建失败
我想给每个商品的规格创建对应的颜色数组——每个商品有多个规格,每个规格对应多种带库存的颜色。但用createMany方法创建失败,尝试先create再createMany也无法成功。
Prisma Schema定义
model Category { id String @id @default(auto()) @map("_id") @db.ObjectId name String gender String image String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User? @relation(fields: [userId], references: [id]) userId String? @db.ObjectId products Product[] } model Size { id String @id @default(auto()) @map("_id") @db.ObjectId size String? colors Colors[] Product Product? @relation(fields: [productId], references: [id]) productId String? @db.ObjectId } model Colors { id String @id @default(auto()) @map("_id") @db.ObjectId color String? stock Int? size Size? @relation(fields: [sizeId], references: [id]) sizeId String? @db.ObjectId } model Images { id String @id @default(auto()) @map("_id") @db.ObjectId url String Product Product? @relation(fields: [productId], references: [id]) productId String? @db.ObjectId } model Product { id String @id @default(auto()) @map("_id") @db.ObjectId name String description String? rating Int? total_sell Int? sold_out Int? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt images Images[] sizes Size[] category Category? @relation(fields: [categoryId], references: [id]) categoryId String? @db.ObjectId user User? @relation(fields: [userId], references: [id]) userId String? @db.ObjectId packages Package[] @relation(fields: [packageId], references: [id]) packageId String[] @db.ObjectId cartItem CartItem[] ProductRating ProductRating[] }
当前POST请求代码
export async function POST(request: Request) { try { const body = await request.json(); const newProduct = await prisma.product.create({ data: { name: body.name, description: body.description, images: { createMany: { data: [ { url: body.images.url } ] } }, category: { create: { name: body.category.name, gender: body.category.gender } }, sizes: { create: [ { size: body.sizes.size, colors: { createMany: { data: [ { color: body.sizes.colors.color, stock: body.sizes.colors.stock, } ] } } } ] } }, include: { category: true, images: true, sizes: { include: { colors: true } } } }); if (!newProduct) throw NextResponse.json({ message: "Failed creating new product", status: 404, }); return NextResponse.json(newProduct, { status: 200, }); } catch (error) { throw NextResponse.json({ message: "Product Created Failed", error, status: 500, }); } }
问题分析与修复方案
核心问题
- 代码错误地将
body.sizes当作单个规格对象处理,但实际应该是规格数组;同时每个规格下的colors也是颜色数组,不能直接取body.sizes.colors.color这种单个值。 - 嵌套创建时没有正确遍历数组,导致
createMany无法匹配正确的数据结构。
修复后的POST代码
首先确保请求体结构符合以下格式:
{ "name": "示例商品", "description": "商品描述", "images": [{"url": "https://example.com/img1.jpg"}, {"url": "https://example.com/img2.jpg"}], "category": {"name": "上衣", "gender": "男"}, "sizes": [ { "size": "M", "colors": [{"color": "红色", "stock": 10}, {"color": "蓝色", "stock": 20}] }, { "size": "L", "colors": [{"color": "黑色", "stock": 15}] } ] }
然后修改请求处理代码:
export async function POST(request: Request) { try { const body = await request.json(); const newProduct = await prisma.product.create({ data: { name: body.name, description: body.description, // 批量创建图片,直接传入图片数组 images: { createMany: { data: body.images } }, category: { create: { name: body.category.name, gender: body.category.gender } }, // 遍历规格数组,为每个规格创建记录并关联颜色 sizes: { create: body.sizes.map(sizeItem => ({ size: sizeItem.size, colors: { // 批量创建当前规格下的所有颜色 createMany: { data: sizeItem.colors.map(colorItem => ({ color: colorItem.color, stock: colorItem.stock })) } } })) } }, include: { category: true, images: true, sizes: { include: { colors: true } } } }); return NextResponse.json(newProduct, { status: 200 }); } catch (error) { return NextResponse.json({ message: "商品创建失败", error: error instanceof Error ? error.message : String(error), status: 500, }); } }
关键修复点
- 用
map遍历body.sizes数组,为每个规格生成对应的创建参数 - 每个规格下的颜色通过
createMany批量创建,同样用map处理颜色数组的每个元素 - 图片部分改为直接接收数组,支持多图场景
- 优化错误处理逻辑,避免抛出
NextResponse而是直接返回响应
内容的提问来源于stack exchange,提问作者Ahmed Khaled
相关产品推荐
相关产品推荐

