GraphQL error: Attempted to return a null value for a required field in the query

Encountering an issue while querying the memberList resolver. The expected behavior is to return a membeTypeID, but instead it returns null. Apollo is being used for this operation:

    "errors": [
        {
            "message": "Cannot return null for non-nullable field Member.memberType.",
            "locations": [
                {
                    "line": 5,
                    "column": 3
                }
            ],
            "path": [
                "memberList",
                0,
                "memberType"
            ],
            "extensions": {
                "code": "INTERNAL_SERVER_ERROR",
                "stacktrace": [
                    "Error: Cannot return null for non-nullable field Member.memberType.",

The query in use:

query MemberList {
    memberList{
        firstName
        id
        memberType{id}
    }
}

Part of Member Entity with typeORM and Graphql:

 /** Reference to type of member. */
  @ManyToOne(() => MemberType, (memberType) => memberType.memberType, { eager: true })
  // @JoinColumn({referencedColumnName: 'testing'})
  @Field(() => MemberType)
  memberType!: MemberType;

Snippet from member-type entity:

  /** ID number of a member type. */
  @PrimaryGeneratedColumn('increment')
  @Field()
  id!: number;

  /** Type that a member can be. */
  @OneToMany(() => Member, (member) => member.memberType)
  @Field()
  memberType!: string;

The memberList:

 /** Get an array of all members  */
  @Query(() => [ Member ], { nullable: true })
  async memberList(): Promise<Member[] | null>{
    const memberList = await Member.find();
    return memberList;
  }

An error occurs when attempting to run the following mutation:

  /** Update a member with new details */
  @Mutation(() => Member, {nullable: true })
  async memberUpdate(
    @Arg('input') input: MemberUpdateInput,
    @Ctx() { request }: AppContext
  ): Promise<Member | null> {
    input.throwIfInvalid();
    const { userID } = request.session;
    const existingUser = await User.findOneBy({ id: userID });
    if (!existingUser) {
      throw new AuthenticationError;
    }
    // More code here...

Input provided:

{
    "input": {
        "id": "48b76f72-1348-4708-8d09-471cc82def13",
        "firstName": "foob",
        "lastName": "bar",
        "memberType": {
            "id": 2
        },
        "photoUrl": "testingPhoto"
    }
}

Definition of input type MemberUpdateInput:

@InputType()
export class MemberUpdateInput extends UuidInput {
  @Field()
  firstName!: string;
  
  // More fields specified...

Troubleshooting steps taken with no success include making the memberType optional and setting the memberType as a number OneToOne relationship in the Member entity.

Issue seems to stem from the memberType not being retrieved during findbyOne or find queries. Sample output of updatedMember is shown below:

Member {
  createdAt: 2023-10-07T09:56:27.589Z,
  firstName: 'testin',
  githubUrl: null,
  id: '8c636b7b-4d83-4681-a912-87aee5a95c2e',
  lastName: 'bar',
  linkedinUrl: null,
  personalUrl: null,
  photoUrl: 'testThing',
  updateAt: 2023-10-07T09:56:27.589Z,
  memberType: MemberType {
    createdAt: 2023-10-07T09:21:01.670Z,
    id: 1,
    updateAt: 2023-10-07T09:21:01.670Z
  }
}

Result of memberList[0]:

Member {
  createdAt: 2023-10-07T09:56:27.589Z,
  firstName: 'testin',
  githubUrl: null,
  id: '8c636b7b-4d83-4681-a912-87aee5a95c2e',
  lastName: 'bar',
  linkedinUrl: null,
  personalUrl: null,
  photoUrl: 'testThing',
  updateAt: 2023-10-07T09:56:27.589Z,
  memberType: MemberType {
    createdAt: 2023-10-07T09:21:01.670Z,
    id: 1,
    updateAt: 2023-10-07T09:21:01.670Z
  }
}

Answer №1

Oops, I accidentally placed the OneToMany relationship on the wrong column in the member type entity:

Check out the revised MemberType entity below:


  /** Unique ID of a member type. */
  @PrimaryGeneratedColumn('increment')
  @OneToMany(() => Member, (member) => member.memberType)
  @Field()
  id!: number;

  /** Classification of a member. */
  @Column()
  @Field()
  memberType!: string;

Now, let's take a look at the Member entity's memberType Column:


  /** Relationship to member type. */
  @ManyToOne(() => MemberType, (memberType) => memberType.id, { eager: true })
  @JoinColumn({name: 'memberTypeID'})
  @Field(() => MemberType)
  memberType!: MemberType;

Here is an example of how to query the data correctly now:


query MemberList {
    memberList{
        firstName
        id
        memberType{
            memberType
        }
    }
}

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

Resolving issues with ESLint error related to Promise executor functions

Two warnings are triggered by the code block below ESLint Warning: Avoid using async function as Promise executor. (no-async-promise-executor) ESLint Warning: Function argument expects void return, but returns a Promise instead. (@typescript-eslint/no-mis ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

Is including takeUntil in every pipe really necessary?

I'm curious whether it's better to use takeUntil in each pipe or just once for the entire process? search = (text$: Observable<string>) => text$.pipe( debounceTime(200), distinctUntilChanged(), filter((term) => term.length >= ...

The 'ngForOf' directive cannot be bound to 'div' element as it is not recognized as a valid property

Encountering an issue with adding an ngFor directive on a div, which is causing a warning and preventing my HTML from rendering properly. I experimented with using *ngFor on various elements like <li>, <tr>, and <span>, but kept getting ...

encountering difficulties calling setAttribute within a function

I am encountering an issue while attempting to use setAttribute() within toggleDiv(). My IDE does not seem to recognize the function and is throwing an error. How can I resolve this problem so that the function is recognized? This specific case relates t ...

The function was operational before, but currently it is indicating that it is no longer functioning as a

I encountered an issue with my code where a service that was previously working has suddenly stopped functioning and is now displaying an error message stating that it's not a function. Thanks to Sajeetharan for helping me out initially. constructo ...

Incorporate MUX Player (Video) into Angular versions 14 or 15

Mux offers a video API service with its own player: MUX Player I am interested in integrating this npm package specifically into a component in Angular 14/15. The JavaScript should only be loaded when this particular component is rendered. Integration Th ...

Having trouble setting up mongodb-memory-server 8 to work with jest

I am currently working on integrating the latest version of mongodb-memory-server with jest on a node express server. While following the guide provided in the mongodb-memory-server documentation (), I encountered some gaps that I am struggling to fill in. ...

No routes found that match. URL Segment 'calendar' does not correspond to any routes available

Currently interning, I've been tasked with building my own Angular 5 web application. However, I've hit a roadblock with an issue that's had me stuck for hours now. Every time I try to access the calendar, it gives me an error saying it can& ...

The Mat-slide-toggle resembles a typical toggle switch, blending the functionalities of

I am facing an issue with a `mat-slide-toggle` on my angular page. Even though I have imported the necessary values in the module, the toggle is displayed as a normal checkbox once the page loads. HTML: <div style="width:100%;overflow:hidden"> < ...

The TypeScript compiler is unable to locate the module react-scripts within the lerna webpack configuration

Recently, I've been working on setting up a new project using lerna, react-scripts, webpack, and sass. Here is my current directory structure: myApp /packages /myReactApp -> a react create app application /tsconfig.json /package ...

"Ionic 3: Utilizing the If Statement within the subscribe() Function for Increased Results

I added an if conditional in my subscribe() function where I used return; to break if it meets the condition. However, instead of breaking the entire big function, it only breaks the subscribe() function and continues to execute the navCtrl.push line. How ...

Manipulating URL parameters in Angular 2

I have implemented the following code: this.router.navigate(['/app/chart', {chartColor: this.color, chartWidth: this.width}]); Upon executing this code, the URL is set to: http://localhost/app/chart;chartColor=blue;chartWidth=600 Everything s ...

The child component displays an error when input is entered, but occasionally it successfully loads

Currently, I am encountering an issue with passing an object from a parent component to a child component in Angular. Whenever I run the command ng serve, an error is thrown stating that the passed object cannot be found. However, on occasions when I save ...

Serialising and deserialising TypeScript types in local storage

I'm currently working on a Typescript application where I store objects using local storage for development purposes. However, I've run into some trouble with deserialization. Specifically, I have an object called meeting of type MeetingModel: ...

Utilizing type arguments in JSX components when applying withStyles

When working with React and material-ui, I am attempting to create a JSX component that can accept generic parameters while also utilizing the withStyles Higher Order Component (HOC) to inject styles. The initial approach looked something like this: cons ...

Switch on ngbAccordion via TypeScript File

I need to implement a function in my component.ts file that will toggle the accordion using a button. Can you help me with the script for this? This is my HTML code: <button (click)="toggleAcc()" type="button" class="btn btn-pr ...

The module 'AppModule' is importing an unexpected value 'AppAsideModule'. To resolve this issue, make sure to include an @NgModule annotation

Recently, I attempted to upgrade my Angular project from version 13 to version 17. However, during the process, I encountered an error stating "Unexpected value 'AppAsideModule' imported by the module 'AppModule'. Please add an @NgModul ...

ngFor filter based on user input

I am working on a 2-step stepper feature where I need to filter the values in my amountArray based on the age of the person. If the person is above 50 years old, display only the values 10000 and 15000. For Euro currency, show values 25000 and 50000. I att ...

Create a new object containing a series of function expressions, but exclude the first function parameter

In my current setup, I have a variable called storePattern const storePattern = { state: { }, mutations: { }, actions: {}, modules: { modal: { actions: { openModal(store, name: string): boolean { console.log('Op ...