prismaprisma-graphqlprisma2graphql-playground

findUnique query returns null for array fields


I read the Prisma Relations documentation and it fixed my findMany query which is able to return valid data but I'm getting inconsistent results with findUnique.

Schema

model User {
  id       Int       @id @default(autoincrement())
  fname    String
  lname    String
  email    String
  password String
  vehicles Vehicle[]
}

model Vehicle {
  id      Int    @id @default(autoincrement())
  vin     String @unique
  model   String
  make    String
  drivers User[]
}

Typedefs

const typeDefs = gql'
    type User {
      id: ID!
      fname: String
      lname: String
      email: String
      password: String
      vehicles: [Vehicle]
    }

    type Vehicle {
      id: ID!
      vin: String
      model: String
      make: String
      drivers: [User]
    }

    type Mutation {
      post(id: ID!, fname: String!, lname: String!): User
    }

    type Query {
      users: [User]
      user(id: ID!): User
      vehicles: [Vehicle]
      vehicle(vin: String): Vehicle
    }
'

This one works

users: async (_, __, context) => {
        return context.prisma.user.findMany({
          include: { vehicles: true}
        })
      },

However, for some reason the findUnique version will not resolve the array field for "vehicles"

This one doesn't work

user: async (_, args, context) => {
     const id = +args.id
     return context.prisma.user.findUnique({ where: {id} }, 
         include: { vehicles: true}
     )
},

This is what it returns

{
  "data": {
    "user": {
      "id": "1",
      "fname": "Jess",
      "lname": "Potato",
      "vehicles": null
    }
  }
}

I was reading about fragments and trying to find documentation on graphql resolvers but I haven't found anything relevant that can solve this issue.

Any insight would be appreciated! Thanks!


Solution

  • You need to fix the arguments passed to findUnique. Notice the arrangement of the { and }.

    Change

    return context.prisma.user.findUnique({ where: { id } },
      //                                                  ^
      include: { vehicles: true}
    )
    

    to

    return context.prisma.user.findUnique({
      where: { id }, 
      include: { vehicles: true }
    })