Is the Prisma model not reachable through Prisma Client?

I'm currently attempting to retrieve a specific property of a Prisma model using Prisma Client. The model in question is related to restaurants and includes a reviews property that also corresponds with a separate Review model.

schema.prisma file:

// This here is your Prisma schema document,
// read further about it in the documentation: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Restaurant {
  id          Int      @id @default(autoincrement())
  name        String
  main_img    String
  images      String[]
  description String
  price       PRICE
  opens_at    String
  closes_at   String
  slug        String   @unique
  created_at  DateTime @default(now())
  updated_at  DateTime @updatedAt
  item        Item[]
  location_id Int      @unique
  location    Location @relation(fields: [location_id], references: [id])
  cuisine_id  Int      @unique
  cuisine     Cuisine  @relation(fields: [cuisine_id], references: [id])
  review_id   Int      @unique
  reviews     Review[]
}

... (repeated various other schemas)

enum RATING {
  HALF
  ONE
  ONE_HALF
  TWO
  TWO_HALF
  THREE
  THREE_HALF
  FOUR
  FOUR_HALF
  FIVE
}

The objective is to execute queries on this schema from a page.tsx file by leveraging the Prisma client.

Interacting with Prisma Client:

import { PrismaClient, Cuisine, Location, PRICE, Review } from "@prisma/client";

const prisma = new PrismaClient();

export interface IRestaurantCardType {
  id: number;
  name: string;
  price: PRICE;
  main_img: string;
  location: Location;
  cuisine: Cuisine;
  slug: string;
  reviews: Review[];
}


const fetchRestaurants = async (): Promise <IRestaurantCardType[]> => {
  const restaurants = await prisma.restaurant.findMany({
    select: {
      id: true,
      name: true,
      price: true,
      main_img: true,
      location: true,
      cuisine: true,
      slug: true,
      reviews: true,
    }
  });

  return restaurants;
};

However, there are two issues arising from the provided code. The first problem involves an error within the import declaration, specifically when attempting to import the Review type.

Module '"@prisma/client"' has no exported member 'Review'.ts(2305)
The remainder of the imports do not trigger this particular error.

The second issue occurs within the fetchRestaurants function, specifically pertaining to the object restaurants in the select property at reviews: true,.

Type '{ id: true; name: true; price: true; main_img: true; location: true; cuisine: true; slug: true; reviews: true; }' is not assignable to type 'RestaurantSelect'.
  Object literal may only specify known properties, and 'reviews' does not exist in type 'RestaurantSelect'.ts(2322)

I am employing Next.js 13 with the experimental app directory structure in combination with Prisma for my ORM operations based on Postgres.

Update:

I managed to remove the node_modules directory and reinstated it through running npm install, thereby resolving both errors. Nonetheless, if I attempt to log restaurants.reviews, it returns as undefined. Additionally, inspecting the restaurants variable reveals the reviews property returning as reviews: [ [Object] ].

Answer №1

  • One possible issue could be that you forgot to migrate after adding the Review model. Make sure to execute the following command:

    npx prisma db push
    

Refer to this documentation for more information: here

The 'db push' command utilizes the same engine as Prisma Migrate to synchronize your Prisma schema with your database schema. It performs the following tasks:

1- Analyzes the database structure and implements the necessary changes to align it with your Prisma schema.

2- By default, once the database schema is updated, generators like Prisma Client are triggered automatically. There is no need to manually run 'prisma generate'.

  • If you want to generate types using Prisma, run the following command:

    npx prisma generate
    

Lastly, remember to restart the server after performing these steps.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered in React component: TypeScript TS2339 states that the property 'xyz' is not found on type 'IntrinsicAttributes...'

I am attempting to develop a straightforward React component that can accept any properties. The syntax below using any is causing issues (unexpected token just before <): export class ValidatedInput extends React.Component<any, any> {...} The p ...

Route protection is ineffective when dealing with two observables simultaneously

After writing the route guard as shown below, I encountered an issue with the else statement that was not returning a result, even though it should have. Surprisingly, there were no errors either. this.hotelSettingsService.get().pipe(map(res => { ...

Leveraging vue-devtools in combination with the composition-api while implementing a render function (such as JSX)

Ever since I made the transition to utilizing the composition-api and incorporating a render function (primarily leveraging JSX with TypeScript for type safety within the template), I've encountered an issue where vue-devtools cannot inspect the compu ...

`The Art of Curved Arrows in sigjma.js, typescript, and npm`

I have encountered an issue while trying to draw curved arrows in sigma.js within my TypeScript npm project. The error occurs on the browser/client-side: Uncaught TypeError: Cannot read properties of undefined (reading 'process') at Sigma.pro ...

Vercel deployment issue: Hidden input values not being detected as expected

Whenever I attempt to update the data on Vercel, an error message is displayed: invalid input syntax for type uuid: "undefined" - unable to save Oddly enough, the data updates successfully when done locally. This is how I submit the form: <form onSu ...

Is there a way to eliminate text from a barcode image using JavaScript or TypeScript?

This is my unique html code <div class="pr-2" style="width: 130px"> <div *ngIf="!element.editing" > <span class="ss">{{element.barcode}}</span> </di ...

Running create-next-app in a container results in failure

I am trying to initiate a new nextjs app in my current directory on the host system without having to install node, etc. To achieve this, I decided to run a container using the following command: docker run --rm -it -v $(pwd):/app node:17.8.0 bash Upon ch ...

Displaying the ngFor data in the HTML section

Struggling with passing an array from poll-vote.component.ts to poll-vote.component.html. The data involves radio buttons and I'm using ngFor loop with index, but it's not working as expected: Here is my poll-vote.component.ts code: import { Com ...

I find myself hindered by TypeScript when trying to specify the accurate constraints for getUserMedia

I'm having difficulty getting a screen to stream within my Angular 5 Electron application. I am utilizing the desktopCapturer feature provided by Electron. Below is an excerpt of my code: loadCurrentScreensource() { desktopCapturer.getSources({ ...

Tips for using the fetch() method to send an object to a dynamic API route in Next.js

I'm running into a problem when trying to send an object to my dynamic API route in Next.js. Everything works fine when sending a regular string, and I can update my MongoDB without any issues. However, when attempting to send an object, the request d ...

Searching for multiple items in Postgres Json can be achieved by utilizing the JSONB data

In my Postgres DB, I store data in a json column called items which keeps all the information in a single row. [ { "item_code":"UMI MAIZE Box (10.0 PC)", "name":"5e0648a9e5", "uom":null ...

TypeScript properties for styled input component

As I venture into TS, I’ve been tasked with transitioning an existing JS code base to TS. One of the challenges I encountered involves a styled component in a file named style.js. import styled from "styled-components"; export const Container ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

VS Code is flagging TypeScript errors following the recent software update

After updating my VS Code, I started seeing TypeScript error messages like the following: ButtonUnstyled.types.d.ts: Module '"/components/node_modules/@types/react/index"' can only be default-imported using the 'esModuleInterop&a ...

Deduce the generic types of conditional return based on object property

My goal is to determine the generic type of Model for each property. Currently, everything is displaying as unknown[] instead of the desired types outlined in the comments below. playground class Model<T> { x?: T } type ArgumentType<T> = T ...

Encountering an Uncaught Error: MyModule type lacks the 'ɵmod' property

I am currently working on developing a custom module to store all my UI components. It is essential that this module is compatible with Angular 10 and above. Here is the package.json file for my library: { "name": "myLibModule", &qu ...

Regular expression for the validation of emails using a delimiter

Can someone help me create a regex expression for emails? This is what I have so far: \S+@\S+\.\S+ I want to repeat this X times with a ; separator. Any ideas on how to achieve this? For example, the pattern should allow strings like: ...

Combining Typescript interfaces to enhance the specificity of a property within an external library's interface

I have encountered a scenario where I am utilizing a function from an external library. This function returns an object with a property typed as number. However, based on my data analysis, I know that this property actually represents an union of 1 | 2. Ho ...

Spreading an object to remove a key may result in the returned value being

When creating a Radio Button object, each object in the array consists of {value: 1, text: 'Sometext'}. If a radio button is selected, 'selected: true' is added to that specific object and removed from the others. const onChoiceChange ...

What steps should I take to resolve the 'CLIENT_FETCH_ERROR' when encountering it in Next Auth Google login while using the getSession function?

I have been working on a Next.js application and integrating Next Auth Google login. The process went smoothly until I encountered an error when using the getSession function in the backend: [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/ ...