简体   繁体   中英

Select specific fields in Prisma not working

I would like to select specific fields

return this.prisma.user.findFirst({
  where: {
    password_hash: createHash('md5')
      .update(`${userId.id}test`)
      .digest('hex'),
  },
  select: {
    name: true,
    email: true,
  },
});

But I'm getting this Typing error

Type '{ name: string; email: string; }' is missing the following properties from type 'User': id, password_hash

Here's the type definition of the user

export type User = {
  id: number
  name: string
  email: string
  password_hash: string
}

You are returning the wrong type in the function from which you are calling it. If you add a select clause, the returned result is thinned out to the properties of your select, while you pretend to return a full User from the wrapping function:

// The full user:
type User = {
  id: number
  name: string
  email: string
  password_hash: string
}

// Here you pretend to return a full user:
function getUser(userId): Promise<User | null> {
  return this.prisma.user.findFirst({
    where: {
      password_hash: createHash('md5')
        .update(`${userId.id}test`)
        .digest('hex'),
    },
    select: { // Here you remove some properties from the user:
      name: true,
      email: true,
    },
  });
}

You can fix it by changing the return type:

function getUser(userId): Promise<{ name: string, email: string } | null> {
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM