GraphQL Nexus Schema fails to retrieve related fields from TypeORM Entity Association, returning null instead

Currently in the process of constructing a GraphQL API using TypeORM and Nexus Schema. I have set up various entities with relationships between them including Product, Brand, and User. The challenge I'm encountering is that when querying the Product entity through GraphQL, fields like category_id and brand_id are coming back as null even though there is data stored in the database.

Below is a snippet of the GraphQL Nexus Schema:

// ProductType.ts
import { objectType } from 'nexus';
import { context } from './context';
import { User } from './User';

export const ProductType = objectType({
  name: 'Product',
  definition(t) {
    t.nonNull.int('id');
    t.nonNull.string('name');
    t.int('creatorId');
    t.nonNull.int('category_id');
    t.nonNull.int('brand_id');

    t.field('createdBy', {
      type: 'User',
      resolve(parent, _args, _context: context, _info): Promise<User | null> {
        return User.findOne({ where: { id: parent.creatorId } });
      },
    });

  },
});

Brand Entity:

//brand.ts
import {
  BaseEntity,
  Entity,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  PrimaryGeneratedColumn,
  ManyToOne,
  OneToMany,
} from 'typeorm';
import { User } from './User';
import { Product } from './Product';
import { OrderItem } from './OrderItem';

@Entity()
export class Brand extends BaseEntity {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column({ unique: true })
  name!: string;

  @OneToMany(() => Product, (product) => product.brand)
  products: Product[];

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}

Product Entity:

import {
  BaseEntity,
  Entity,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  PrimaryGeneratedColumn,
  OneToMany,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { User } from './User';
import { Wishlist } from './Wishlist';
import { Review } from './Review';
import { OrderItem } from './OrderItem';
import { Brand } from './Brand';
import { Category } from './Category';
import { ProductImage } from './ProductImage';

// Code for Product entity here...

After double-checking the database, it is confirmed that both category_id and brand_id contain data. Nevertheless, these fields are returning null when querying the Product entity. I've reviewed my entity associations and definitions but am unable to identify the root cause of this issue.

If anyone can shed light on why the related fields are showing null values despite the database having the necessary information, your assistance would be greatly appreciated. Any advice or suggestions will be valuable. Thank you!

Answer №1

It was necessary to specifically identify the column name as brandId and columnId

@Column()
  brandId!: number;
  @ManyToOne(() => Brand, (brand) => brand.products)
  brand: Brand;

  @Column()
  categoryId!: number;
  @ManyToOne(() => Category, (category) => category.products)
  category: Category;

Following that, changes were made to update the required names in the schema.

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

Attempting to showcase the data stored within MongoDB documents on my website's user interface

I am facing difficulties in showing the data stored in my database on the front end of my grocery list app, which is built using the MERN stack. I have a form that successfully sends data to MongoDB and saves it upon submission. In order to retrieve the d ...

Uploading CSV or text files in Node.js

I am looking to develop a function that can upload CSV or txt files into MongoDB using the MEAN stack. The function should work by allowing me to upload a file, then it will verify if it is in text/csv format before uploading it to MongoDB. I have attemp ...

Dealing with API responses that are compressed with .gzip and contain XML files

I'm currently facing challenges in managing API interactions using node.js (with express and request) due to difficulties handling the data. Below is the snippet of my code: // Requirements const express = require("express"); const bodyParser = re ...

Troubleshooting issue: relationship between models not functioning in Express.js when using Sequelize

I have created models Skills and Members Member Table: id username password created 1 gagandeep 99703dd91da5b0cabf496d49af0ab03c2dfe7788 2017-08-14 05:59:46 Skills Table: id member_id skill 1 1 programming 2 1 music Code: Mod ...

Alter the hyperlink to a different value based on a specific condition

I need help with implementing a login feature on my app. The idea is that when the user clicks the login button, it should trigger a fetch request to log in with their credentials. If the login is successful, the button's value should change to redire ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...

Having trouble executing Token-based authentication-passport code in NodeJS and ExpressJS

app.js const express = require('express'); const path = require('path'); const logger = require('morgan'); const app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app ...

What causes the occurrence of the Error [ERR_HTTP_HEADERS_SENT]?

Encountering an issue when adding authentication to my project. This particular controller relies on a middleware for user authentication. exports.fetchOne = (req, res) => { const _id = req.params.id; console.log("fetch One"); try { ...

"Develop an API using NodeJs and Mongoose where every request is seamlessly directed to another collection

I am currently developing a Node.js API for an app that involves users, and I want each user to have their own MongoDB collection. Currently, everything is functioning properly. However, I notice that when I access collections dynamically, the process slo ...

The issue with res.sendFile is that it is failing to display

I have encountered an issue while attempting to render HTML with res.sendFile using an absolute path. The encoded HTML is being displayed unrendered within a pre tag in the response. Below is the express code I am currently using: app.get('/', ( ...

Error: Callback function in Mongoose Populate is returning undefined

I have a query set up in MongoDB where I am trying to display all subcollections of the schema while excluding the account ID. The issue is that I am getting "undefined" as the result for the callback "list_data". Here is how my query looks in my routes: ...

The redirection feature in nodejs/expressjs does not seem to function properly

I attempted to use the redirect function in expressjs to serve a webpage, but for some reason it's not functioning properly. I must be missing something here. index.html: <html> <body> <div id="clicked"> not clicked </div&g ...

Using React.js to add MongoDB documents into the database

Is there a way to directly insert documents into a MongoDB collection from a React component? I have been working on a personal project, which is a chat web application used for training purposes. For instance, when a user wants to post a new message in a ...

Tips on obtaining a Firebase ID

Does anyone have a solution for retrieving the unique id from Firebase? I've attempted using name(), name, key, and key() without any success. Although I can view the data, I'm struggling to find a way to retrieve the id. This information is cru ...

Using promises and the fetch function to connect to a database

I am attempting to utilize promises with the fetch() function in order to access MongoDB from the front-end, but I am encountering some issues. var Promise = () => ( new Promise((resolve, reject) => { //perform certain actions, make requests ...

Experiencing difficulties with res.redirect function in Express framework

After numerous attempts to enter my location into the search form, I noticed that while it logs in the console, the res.redirect function fails to take me to a new URL. My goal was to be redirected to a different webpage after submitting my location info ...

Understanding NodeJS Code

As a newcomer to nodejs, I've been delving into some code and trying to grasp its concepts. Could someone kindly guide me in understanding the following code snippets? My inquiries might be basic, but please note that I'm on a learning curve with ...

Running a function synchronously in Node.js and Express can be challenging

For my project, I utilized the wikipedia-js library. Below is the code snippet from my summary.js file. var wikipedia = require("wikipedia-js"); var something = "initial"; module.exports = { wikitext: function(topicname) { console.log("Inside ...

What could be causing the malfunction in this JavaScript and WebRTC code?

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vid Chat App</title> </head> <body> <video controls autoplay> </video> <script src="https: ...

JSON does not display the full stack trace in logs

Here is my approach to setting up log4js: import log4js from 'log4js'; const logger = log4js.getLogger(); log4js.configure({ appenders: { log: { type: 'file', filename: 'logTofile.json' } }, categories: { default: { appen ...