The Problem
Currently, you can only write data using prisma.create and then individually writing out the fields and their values. But I want to be able to simply write data by providing an object. This way if I already have the object I want to put in my database, I don't have to individually add its fields.
The Solution
The solution would be a prisma.create function that allows input of an object. For example, if my database schema already contains a user with fields name and age, I want to be able to write a new user in the database by calling (in JS)
user = {name: "Tade", age: 3};
await prisma.createUser({user})
as opposed to
await prisma.createUser({name: "Tade", age: 3})
This is particularly useful for objects that have a lot of nested fields.
@Gazuntype
Can you please tell me why are not doing await prisma.createUser(user)? Just pass the object directly to the function.
@pantharshit00 because it doesn't work if the user has nested fields of different types. For example if the user schema is
type User {
id: ID! @unique
createdAt: DateTime!
name: String!
car: [Car!]!
}
type Car{
id: ID! @unique
name: String!
engine: String!
And I have a user object as
const user = {
name: "Tade"
car: [{
name: "Volkswagen"
engine: "V6"
},
{
name: "Mercedes"
engine: "V4"
}]
}
If I do await prisma.createUser(user), I will get an error similar to the one below because of the nested types
"Expected 'UserCreateInput', found not an object. (line 1, column 11):"
@Gazuntype Even though if we enable object API(which makes no sense) this will still not work as your data is not properly structured.
Try this
const user = {
name: "Tade"
car: [{
name: "Volkswagen"
engine: "V6"
},
{
name: "Mercedes"
engine: "V4"
}]
}
await prisma.createUser({...user, car: { create: user.car });
Hm. That makes sense. I'll try it out to see if it works. Sorry for the bother but just one more question because my real use case is slightly more complex. If the engine was another type, for example
type User {
id: ID! @unique
createdAt: DateTime!
name: String!
car: [Car!]!
}
type Car{
id: ID! @unique
name: String!
engine: Engine!
type Engine{
type: String!
}
And my object is
const user = {
name: "Tade"
car: [{
name: "Volkswagen"
engine: {
type: "V6"
}
},
{
name: "Mercedes"
engine: {
type: "V4"
}
}]
}
What would the prisma create command look like? Cos now I have to create a type within an array within an object. If that makes sense. Thanks for your help so far, by the way.
Structure your user object like so:
const user = {
name: "Tade",
car: {
create: [
{
name: "Volkswagen",
engine: {
create: {
type: "V6"
}
}
},
{
name: "Mercedes",
engine: {
create: {
type: "V4"
}
}
}
]
}
};
Hm hm. Looks like that should work. Thanks.
Most helpful comment
Structure your user object like so: