Error message: The database query function is encountering an issue where the property 'relation.referencedTable' is undefined and cannot be accessed

Currently, I am working with two schemas named products.ts and category.ts. The relationship between these files is defined as one-to-many.

In the products.ts file:

import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core";
import { categories } from "./category";
import { relations } from "drizzle-orm";

// Code snippet defining the products table...

export const productsRelations = relations(products, ({ one }) => ({
    category: one(categories,{
        fields: [products.categoryId],
        references: [categories.id],
    })
}))

// Additional type definitions related to products...

In the category.ts file:

import { relations } from "drizzle-orm";
import { pgTable, timestamp, uniqueIndex, uuid, varchar } from "drizzle-orm/pg-core";
import { products } from "./product";

// Code snippet defining the categories table...

export const categoriesRelations = relations(categories, ({ many }) => ({
    products: many(products)
}))

// Additional type definitions related to categories...

However, an error occurs when attempting to run the query findMany on the categories table:

 await db.query.categories.findMany({
      with: {
        products: true,
      },
    });

https://i.sstatic.net/H4ht7.png

I would appreciate any assistance in resolving this issue. The desired outcome is to have the data retrieved by the query displayed as follows:

type CategoryWithProducts = {
    id: string;
    name: string | null;
    createdAt: Date;
    updatedAt: Date | null;
    products: Products[];
}

Answer №1

It would be ideal if Drizzle could provide a more specific error message, but from what I understand, this indicates that Drizzle is not recognizing any connection between categories and products.

A common mistake in setup is only importing the schemas into your Drizzle client.

For instance, if you currently have:

const db = drizzle(client, {
    schema: {
       products,
       categories,
    },
});

Then your relationships are not being imported into Drizzle, resulting in the error you're encountering.

Instead, you should have:

const db = drizzle(client, {
    schema: {
       products,
       productsRelations,
       categories,
       categoriesRelations,
    },
});

I can't guarantee that this is the issue you're facing, but I hope it provides assistance to you or someone else!

Answer №2

Big thanks to @elbajo, your solution really made a difference for me :-)

Check out this handy tip to retrieve all schemas and relations at once:

import * as schema from './schema.js'
import * as relations from './relations.js'
const client = postgres(process.env.POSTGRES_URL)

export const db = drizzle(client, {
    schema: {
        ...schema,
        ...relations,
    }
});

(Give those upvotes to elbajo's fantastic answer)

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

Having trouble accessing a JSON object with Typescript in an Angular 2 project

Something strange is happening with my code. I am working with a JSON object: {"login":"admin","name":"Admin"} And this is the relevant part of my code: private _userData: User; ... private getUserData() { this._userInfoService.getUserInfo() ...

Exporting a Typescript class from one module and importing it into another module

I am encountering issues with my source tree structure, as outlined below: /project/ |- src/ |- moduleA |- index.ts |- classA.ts (which includes a public function called doSomething()) |- moduleB |- classB.ts Th ...

Can you determine the size of an unknown array in TypeScript?

Currently diving into TypeScript and tackling some TDD challenges. Within my model file, I'm working with a property named 'innovatorQuotes' that should be an array containing strings with a fixed length of 3. I'm struggling to nail dow ...

Data from Rails 6 is not appearing on Heroku's local environment or within the application

I recently attempted to deploy a Rails backend and React frontend application on Heroku. While the frontend functions properly, I am facing issues with data not displaying on the Heroku site and when using heroku local. Strangely enough, everything works p ...

What purpose does the array.pop()!(object) syntax serve within Codemirror?

Within the Codemirror 6 documentation and at line 41 of the code, there is a snippet that reads: while (pending.length) pending.pop()!(data.updates) I'm curious about the meaning of this syntax. It appears to be TypeScript specific. How would this lo ...

Testing the receiveMessage function in SQS using Jest unit tests

Struggling to find the right approach for unit testing this function. I almost have it, but can't quite nail it down. Take a look at the function below: receiveMessage(callback: Function): any { this.sqs.receiveMessage( this.params, ...

When switching tabs, Ion-select should not reload the selected name

Whenever I switch tabs and then return to the previous tab in Ionic, the select field that was previously set becomes null, even though the page is still loading and the variable is populated. <ion-header color="primary"> <ion-navbar> &l ...

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...

The inference of optional generic types is not occurring

I need help addressing a type error in my TypeScript wrapper for handling NextJS API requests. Specifically, I am facing an issue when trying to pass a single type for one of the generic types in the function. To illustrate this error, I have created a si ...

Update current properties of objects

I'm feeling like I'm going crazy and could really use some assistance. My predicament involves a function that looks like this: private generateTimeObject(firstObject: someInterface, secondObject?: someInterface) { let firstTime; let secondTi ...

Struggling to figure out webhooks with Stripe

I have encountered a strange issue while using Stripe webhooks to process payments on my website. When I set the currency to USD, it prompts me to provide an address outside of India, which is expected. However, when I change the currency to INR, the addre ...

String interpolation can be used to easily accept numbers with dot separators

Is it possible to create a function that can accept numbers with dot separators? Here are some examples: func('100.000.002.333') // should pass func('10') // should pass func('20') // should pass func('100') // shou ...

Encountering an issue while using Django, Heroku, and Postgres with the createsuperuser command. The error message reads: "psycopg2.errors.UndefinedTable: relation 'users_profile' does not exist."

After successfully deploying my Django app on Heroku with PostgreSQL, I encountered an issue when trying to create a superuser. The error message "relation 'users_profile' does not exist" appeared, pointing to a problem in the signals.py file. ( ...

Issue: The function "MyDocument.getInitialProps()" needs to return an object containing an "html" prop with a properly formatted HTML string

Check out my project on GitHub at https://github.com/Talita1996/NLW4 To start the project, I used the command yarn create next-app project_name I made changes to some files by modifying their extensions and adding new code Next, I added typescript to the ...

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...

Angular does not update the progress bar

Imagine having a component html with your own customized round progress bar <round-progress #progress [current]="current" </round-progress> The "Current" value represents the percentage. In my TypeScript component, I have written: ...

Ways to resolve issues related to null type checking in TypeScript

I am encountering an issue with a property that can be null in my code. Even though I check for the value not being null and being an array before adding a new value to it, the type checker still considers the value as potentially null. Can anyone shed lig ...

When intercepted, the HttpRequest is being canceled

Solution Needed for Request Cancellation Issue Encountering a problem with the usage of HttpInterceptor to include the Authorize header in all HTTP requests sent to AWS API Gateway. The issue arises as all these requests are getting cancelled when interce ...

Is the performance impacted by using try / catch instead of the `.catch` observable operator when handling XHR requests?

Recently, I encountered an interesting scenario. While evaluating a new project and reviewing the codebase, I noticed that all HTTP requests within the service files were enclosed in a JavaScript try / catch block instead of utilizing the .catch observable ...

Display a fixed three levels of highchart Sunburst upon each click in Angular8

Looking to create a dynamic sunburst highchart that displays three levels at a time while allowing interactive drilling. For instance, if there are 5 levels, the chart should initially show the first three levels. When clicking on level 3, levels 2, 3, and ...