The specified expression for the `instanceof` operator does not evaluate to an object

I have been practicing with nestjs to convert a ReST API to GraphQL, but I keep encountering an error whenever I attempt to fetch data from my GraphQL API using the playground:

"errors": [ { "message": "Right-hand side of 'instanceof' is not an object", "locations": [ { "line": 2, "column": 3 } ], "path": [ "lesson" ], "extensions": { "code": "INTERNAL_SERVER_ERROR", "exception": { "stacktrace": [ "TypeError: Right-hand side of 'instanceof' is not an object", " at MongoEntityManager. (C:\Users\Oluyinka\Desktop\graphql-mongodb\node_modules\typeorm\entity-manager\MongoEntityManager.js:159:51)", " at step (C:\Users\Oluyinka\Desktop\graphql-mongodb\node_modules\tslib\tslib.js:143:27)", " at Object.next (C:\Users\Oluyinka\Desktop\graphql-mongodb\node_modules\tslib\tslib.js:124:57)", " at C:\Users\Oluyinka\Desktop\graphql-mongodb\node_modules\tslib\tslib.js:117:75", " at new Promise ()", " at Object.__awaiter (C:\Users\Oluyinka\Desktop\graphql-mongodb\node_modules\tslib\tslib.js:113:16)", " at MongoEntityManager.findOne (C:\Users\Oluyinka\Desktop\graphql-mongodb\node_modules\typeorm\entity-manager\MongoEntityManager.js:153:24)", " at MongoRepository.findOne (C:\Users\Oluyinka\Desktop\graphql-mongodb\node_modules\typeorm\repository\MongoRepository.js:57:29)", " at LessonService.getLesson (C:\Users\Oluyinka\Desktop\graphql-mongodb\dist\lesson\lesson.service.js:26:44)", " at LessonResolver.lesson (C:\Users\Oluyinka\Desktop\graphql-mongodb\dist\lesson\lesson.resolver.js:24:35)" ] } } } ], "data": null }

Here is the code snippet:

lesson.entity.ts

import { Column, Entity, ObjectIdColumn, PrimaryColumn } from 'typeorm';

@Entity()
export class Lesson {
  @ObjectIdColumn()
  _id: string;

  @PrimaryColumn()
  id: string;

  @Column()
  name: string;

  @Column()
  startDate: string;

  @Column()
  endDate: string;
}

lesson.service.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Lesson } from './lesson.entity';
import { v4 as uuid } from 'uuid';

@Injectable()
export class LessonService {
  constructor(
    @InjectRepository(Lesson) private lessonRepository: Repository<Lesson>,
  ) {}

  async getLesson(id: string): Promise<Lesson> {
    return await this.lessonRepository.findOne({ id });
  }

  async getLessons(): Promise<Lesson[]> {
    return this.lessonRepository.find();
  }

  async createLesson(name, startDate, endDate): Promise<Lesson> {
    const lesson = this.lessonRepository.create({
      id: uuid(),
      name,
      startDate,
      endDate,
    });
    return await this.lessonRepository.save(lesson);
  }
}

lesson.resolver.ts

import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { LessonService } from './lesson.service';
import { LessonType } from './lesson.type';

@Resolver((of) => LessonType)
export class LessonResolver {
  constructor(private lessonService: LessonService) {}
  @Query((returns) => LessonType)
  lesson(@Args('id') id: string) {
    return this.lessonService.getLesson(id);
  }

  @Query((returns) => [LessonType])
  lessons() {
    return this.lessonService.getLessons();
  }

  @Mutation((returns) => LessonType)
  createLesson(
    @Args('name') name: string,
    @Args('startDate') startDate: string,
    @Args('endDate') endDate: string,
  ) {
    return this.lessonService.createLesson(name, startDate, endDate);
  }
}

lesson.type.ts

import { Field, ID, ObjectType } from '@nestjs/graphql';

@ObjectType('Lesson')
export class LessonType {
  @Field((type) => ID)
  id: string;

  @Field()
  name: string;

  @Field()
  startDate: string;

  @Field()
  endDate: string;
}

Answer №2

It seems like your @nestjs/common,@nestjs/core, and @nestjs/platform-express versions have reverted back to major version 7, while @nestjs/graphql and @nestjs/typeorm are still at major version 8. It's important to keep these major versions in sync to avoid potential errors.

Additionally, please note that TypeORM does not support Mongo v4, so ensure you have Mongo v3 installed as Jesse suggested.


My assumption is that you initially created a new project using Nest CLI on v7, and then added the graphql and typeorm packages for Nest which automatically installed their latest versions, v8. To prevent this issue in the future, consider upgrading your Nest CLI to version 8.

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

Issue 1068: Attribute not found within angular 2 (Ahead of Time Compilation)

I am currently learning Angular 2 and trying to create a "User Register" form. However, I encountered an error stating "Property does not exist on type" during Phone number validation. I am using both JIT and AOT compilers. With the JIT compiler, my user ...

Showing JSON data in a JavaScript application using Python's Bottle framework

I've been attempting to retrieve a MongoDB record using a JavaScript function to showcase the document on a webpage. Through the Bottle framework alongside pymongo, my initial approach involved encoding the MongoDB document as a JSON object for passin ...

Can Angular automatically find files for typescript imports?

I've been working with Angular and using TypeScript. When importing a file in Angular, the syntax usually looks something like this: import { MyService } from '../../../folder/child-folder/my-service.service'; As I progress with my project, ...

MongoDB integration with GraphQL does not include the ability to return the _

Greetings everyone! Currently, I am in the process of developing an API using GraphQL and MongoDB. To filter my documents, I have implemented MongoDB aggregation. export const findAllVariants = async (_, { orderby, filter, skip, sort, perPage }, context) = ...

Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implem ...

Dynamically update multilayer markers on X-map using angular-maps

Utilizing Bing Maps (x-map) for displaying data in multiple layers on the map. The markers' data will be updated through a REST API call to the backend. I am facing an issue where the markers do not update on the map despite changing the data source. ...

Transferring data from MongoDB using Data Factory

I have successfully imported JSON service tickets from a MongoDB Atlas collection into Azure Data Factory using a pipeline. The transformation to CSV is also working well, except for one specific mapping requirement. I need to consolidate all worklog-type ...

Add a decorator to all functions in a TypeScript class to list all available methods

How can I apply a decorator function to all methods within a class in order to streamline the code like this: class User { @log delete() {} @log create() {} @log update() {} } and have it transformed into: @log class User { ...

Customize the appearance of pages in Ionic 2 on the fly

In my app, there are 2 different themes based on the subject matter. However, some pages are shared between subjects. Therefore, I need to customize the ion-content based on the subject. I am looking for a solution to allow page-test to switch between dif ...

Securing components in Angular2 with login verification

After wrapping multiple components' ngInit with a check to verify if users are logged in or not, I am looking for a way to avoid repeating the same code. export class ComponentX implements OnInit { constructor(private _authService: AuthService) { ...

Ensure the security of a generic type's value by enforcing type safety

Is there a way to utilize generics to ensure that the type of a value is specific? // Sample array const testArr = [ { id: 3, name: 'Spaghetto', // Type 'string' here shouldNotWork: 3.14, // Type 'number' here ...

Can variables be declared for file paths within the HTML code in a TypeScript file?

We utilize the Vaadin designer to create the frontend of our project. Within the .ts files, we have images where we aim to establish variables for the file paths. Currently, the setup looks like this: <img src="../../themes/light/img/example.jpg&q ...

Encountering an issue following the update from Angular 8 to 12 - receiving the error message: "The 'controls' property is not present in the 'AbstractControl' type."

Previously, I had a fully operational code in Angular 8. Recently, I made the decision to upgrade from version 8 to Angular 12. The main feature of my project is a dynamic reactive form structured in a question-answer format. This form adapts based on the ...

Simplify a user interface

I have a scenario where I need to dynamically derive the keys/fields of my type based on a generic type. For instance: Here are the container interfaces export interface IUser { id: BigInt; name: string; balance: number; address: Address; ...

The useState variable remains unchanged even after being updated in useEffect due to the event

Currently, I am facing an issue in updating a stateful variable cameraPosition using TypeScript, React, and Babylon.js. Below is the code snippet: const camera = scene?.cameras[0]; const prevPositionRef = useRef<Nullable<Vector3>>(null); ...

Encountering issues with dependencies while updating React results in deployment failure for the React app

Ever since upgrading React to version 18, I've been encountering deployment issues. Despite following the documentation and scouring forums for solutions, I keep running into roadblocks with no success. The errors displayed are as follows: $ npm i np ...

Using PersistedModel.create(Array) will generate an object containing properties that are numbered sequentially

Here is a piece of code that makes a call to a Loopback API method with an array of values. The input data is correct, no errors are thrown by the API, and the subscribe block executes as expected. const newStudentGroups = selectedStudentI ...

Create a Referral Program page within a swapping interface similar to the functionalities found in platforms like PancakeSwap, PantherSwap, and

Currently, my goal is to create a referral program page similar to the one found at . I have explored the source code on GitHub for the PantherSwap interface, but unfortunately, I did not come across any references to that specific section. Would you be ...

Typescript: Variable of unspecified type

Within my generator function called foo(), I am making a request to an external API using the fetch method. Once I receive the response data from the API, I then parse it as JSON. Encountering an issue, as Typescript is triggering an error message: An Obj ...

What is the correct way to remove messages from a conversation?

Being new to android development, I hope you'll pardon any naive questions. Currently, I have created a one-on-one messaging app using socket.io and mongodb which is functioning smoothly. It saves a unique room key for two users in the database, acces ...