我正在尝试使用种子脚本为 SQL 数据库提供种子。我的项目 Next.js 与 TypeScript、Faker.js、Prisma ORM 与 Neon PostgreSQL 数据库设置。
架构文件
// schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Product {
id String @id @default(cuid())
name String @unique @db.VarChar(50)
imageUrl String? @default("placeholder.png")
size String @db.Char(1)
color String @db.VarChar(10)
price Decimal? @default(0.00) @db.Money
available Boolean? @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
种子脚本
// /prisma/seed.ts
import { faker } from "@faker-js/faker";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
const SIZES = ["S", "M", "L"] as const;
const COLORS = ["white", "beige", "blue", "green", "purple"] as const;
async function main() {
Array.from({ length: 50 }).map(async (_, i) => {
await prisma.product.createMany({
data: {
name: `${
COLORS[i].slice(0, 1).toUpperCase() + COLORS[i].slice(1)
} shirt ${i}`,
imageUrl: `/assets/products/${COLORS[i]}_${i + 1}.png`,
size: faker.helpers.arrayElement(SIZES),
color: faker.helpers.arrayElement(COLORS),
price: faker.commerce.price({
min: 10,
max: 50,
dec: 2,
// symbol: "$",
// fractionDigits: 2,
}),
available: faker.helpers.arrayElement([true, false]),
},
});
});
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
如果我尝试上传超过 5 个产品
Array.from({ length: 50 }).map(async (_, i) => {...}
,
它返回TypeError: Cannot read properties of undefined (reading 'slice')
我很困惑,如果脚本成功上传了 5 个产品,那么为什么不上传 50 个呢?它的 TypeError 是什么?总体而言如何解决/改进这个问题?
我希望我的问题清晰简洁。尽快寻找解决方案。 谢谢你
在种子文件中,您将
colors
定义为 5 个元素的数组
在为产品生成颜色时,您使用当前数组值的索引
name: `${COLORS[i].slice(0, 1).toUpperCase() + COLORS[i].slice(1)} shirt ${i}`
因此,当进行到第 6 次迭代时,
COLORS[i]
变为 undefined
,因此出现错误 TypeError: Cannot read properties of undefined (reading 'slice')
要解决此问题,请将该行替换为
name: `${COLORS[i % colors.length].slice(0, 1).toUpperCase() + COLORS[i % colors.length].slice(1)} shirt ${i}`