[英]How do you correctly seed a prisma DB with a custom file that has multiple mutations?
[英]Add data from a JSON file to the Prisma database with a seed file
我想用JSON文件中的一些数据为我的数据库建立种子
//continent-data.json
[
{
"continent": "far east",
"imageURL": "#"
},
{
"continent": "ASIA",
"imageURL": "#"
},
]
这是我的seed.js文件
//seed.js
const dotenv = require('dotenv');
const { Prisma } = require('./src/generated/prisma-client');
const continentData = require('./continent-data.json');
dotenv.config();
const db = new Prisma({
secret: process.env.PRISMA_SECRET,
endpoint: process.env.PRISMA_ENDPOINT
});
const seedContinents = () => {
// adding continents to the data
Promise.all(
continentData.map(async continentItem => {
const { imageURL, continent } = continentItem;
const response = await db.createContinent({
data: {
name: continent || 'default name',
imageURL,
}
});
return response;
})
);
};
seedContinents();
当我运行node seed.js
它失败并抛出以下错误
UnhandledPromiseRejectionWarning:错误:'ContinentCreateInput!'类型的变量'$ data'预期值 但得到:{“data”:{“name”:“far east”,“imageURL”:“#”,“destination”:[]}}。 原因:'name'预期的非null值,找到null。
我相信我正在以正确的格式传递正确的数据。 但它说name字段的值为null。 但错误信息本身表示名称字段有一个字符串值“远东”
我也提供了Prisma架构的必要部分。
尝试更改将数据提供给db.createContinent函数的方式。
const response = await db.createContinent({
name: continent || 'default name',
imageURL,
});
只传递数据而不是创建包装器数据对象。
你可以把你在顶部导入的Prisma对象(Prisma客户端)看作辅助类。 在实例化之后,您可以访问javascript函数,这些函数主要反映了根据您的datamodel.graphql
文件为您生成的Prisma Server CRUD函数。
如果查看Prisma客户端页面上的示例文档,您可以看到有两种方法可以传递数据以获得相同的结果 。 一方面你可以调用javascript函数:
db.createContinent({
name: continent || 'default name',
imageURL,
});
另一方面,您可以直接在Prisma端点上运行GraphQL查询,
mutation {
createContinent(data: {
name: continent || 'default name',
imageURL
}) {
name
continent
}
}
第二种方法是在GraphQL操作系统中进行,并直接与数据交互。 使用Prisma客户端自动生成的javascript函数的第一个示例是一个包装器,只需要没有data:object包装器的输入数据。 所以没有了
data: { { ContinentCreateInput object shape }}
文档并没有真正详细介绍它,我花了一段时间才想知道为什么它不适合你在GraphQL类型中指定的形状。
第一种方法是从原始数据库CRUD方法中抽象和保护应用程序层的推荐方法。 请参阅Prisma client
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.