skip to Main Content

I am trying to query my MongoDB database through Prisma. I want to include "property" in my query. Postman is returning the correct data with property data included, but within NextJs app it seems to be undifined or null. My query is:

export async function GET(request: NextRequest) {
    const maintenanceItems = await prisma.maintenance.findMany({
        include: {
            property: true,
        }
    })
    return NextResponse.json(maintenanceItems)
}

This is how i’m calling it

let maintenanceItems: NewMaintenanceIncidentType[] = [];
export const getMaintenanceItems = async () => {
    try {
        const response = await fetch(`${process.env.BASE_URL}/api/maintenance/`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            },
        });
        if (!response.ok) {
            throw new Error("Failed to fetch Maintenance Items");
        }

        maintenanceItems = await response.json();
        console.log("from the server: ", maintenanceItems);

    } catch (error) {
        console.log("Server fetch failed on OpenMaintenanceItemPage ", error);
    }
    return maintenanceItems
};

My Models are:

model Maintenance {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  name        String
  description String 
  status      String
  image       String?
  createdDate DateTime @default(now())
  dueDate     DateTime
  property    Property @relation(fields: [propertyId], references: [id])
  propertyId  String   @db.ObjectId
}

model Property {
  id               String         @id @default(auto()) @map("_id") @db.ObjectId
  propertyType     String 
  streetNumber     String 
  street           String
  postcode         String
  apartmentNumber  String? 
  city             String
  county           String
  propertyCategory String 
  status           String
  maintenanceTasks Maintenance[]
  userProperties   UserProperty[]

}

Here are my types

export type NewMaintenanceIncidentType = {
    id: string,
    name: string,
    description: string,
    status: string,
    image: string,
    createdDate: Date,
    dueDate: Date,
    property: PropertyType,
    reportedBy: string,
    assignedTo: string,
    propertyId: string,
}

export type PropertyType = {
    id: string;
    propertyType: string;
    streetNumber: string;
    street: string;
    postcode: string;
    apartmentNumber: string;
    city: string;
    county: string;
    propertyCategory: string;
    status: string;
}

This is how I’m fetching via Server page

export default async function OpenMaintenanceItemsPage() {
  const openMaintenanceItems = await getMaintenanceItems();

  return (
    <>
      <Typography>Open Maintenance Items Page</Typography>
      <BasicTable openMaintenanceItems={openMaintenanceItems} />
    </>
  );
}

If you need any other info let me know. I have been stuck on this for hours :D:D

thanks

2

Answers


  1. Chosen as BEST ANSWER

    For any one coming back to this in the future...

    Like Radmehr said above, I removed the following from my fetch function:

    headers: {
                    "Content-Type": "application/json",
                },
    

    I found that the the issue however was to do with how Next caches fetch functions. To solve this I added cache: 'no-store'

    const response = await fetch(`${process.env.BASE_URL}/api/maintenance/`, { cache: 'no-store' });
    

    That worked for me


  2. First get a log from ${process.env.BASE_URL}/api/maintenance/ it can have two // after base url.

    Second you don’t need content type in GET method, because you cannot pass data in get method 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search