0

I'm currently following the documentation on NestJS regarding the mongo db implementation. In the example they use a Cats database. Here I'm using a mongo db.

My schema is (categories.schema.ts):

export type CategoriesDocument = Categories & Document;

@Schema({ collection: 'categories' })

export class Categories {
  @Prop()
  id: number;

  @Prop()
  name: string;

  @Prop()
  slug: string;

  @Prop()
  created_at: Date;

  @Prop()
  updated_at: Date;
}

export const CategoriesSchema = SchemaFactory.createForClass(Categories);

I put this into my service in the constructor method:

import { Categories, CategoriesDocument } from './schema/categories.schema';

@Injectable()
export class CategoriesService {
  constructor(@InjectModel(Categories.name) private categoriesModel: Model<CategoriesDocument>) {}
...

In the same service I have:

  async findAll(): Promise<Categories> {
    return this.categoriesModel.find().exec();
  }

I then have a resolver (this is a graphql project) export class CategoriesResolver { constructor(private readonly categoriesService: CategoriesService) {} ...

  @Query(() => Category, { name: 'ocategory' })
  async ogetCategory(
    @Args('id', { type: () => ID }) id: number,
  ): Promise<Category> {
    return this.categoriesService.findAll();
  }

My Mongo collection looks like so:

_id
:
61bbd7dc86e25adaf8235981
id
:
8
name
:
"Nuts & Biscuits"
slug
:
"nuts-biscuits"
icon
:
null
image
:
Array
details
:
null
parent
:
Object
type_id
:
1
created_at
:
"2021-03-08T08:57:28.000000Z"
updated_at
:
"2021-03-08T08:57:28.000000Z"
deleted_at
:
null
parent_id
:
7
type
:
Object
children
:
Array

The error I get is:

src/categories/categories.service.ts:74:5 - error TS2739: Type '(Categories & Document<any, any, any> & { _id: any; })[]' is missing the following properties from type 'Categories': id, name, slug, created_at, updated_at

74     return this.categoriesModel.find().exec();
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Any idea what I'm doing wrong here?

1 Answer 1

1

findAll returns an array. You've told Typescript you expect to return a single object. Update your return type to be Promise<Category[]> and your query to be @Query(() => [Category])

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.