【问题标题】:Pulling data from Mongo DB not functioning as expected从 Mongo DB 中提取数据未按预期运行
【发布时间】:2022-01-26 17:17:27
【问题描述】:

我目前正在关注 NestJS 上关于 mongo db 实现的documentation。在示例中,他们使用 Cats 数据库。这里我使用的是 mongo db。

我的架构是(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);

我在构造方法中把它放到了我的服务中:

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

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

在我拥有的相同服务中:

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

然后我有一个解析器(这是一个 graphql 项目) 导出类 CategoriesResolver { 构造函数(私有只读类别服务:类别服务){} ...

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

我的 Mongo 收藏看起来像这样:

_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

我得到的错误是:

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();
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

知道我在这里做错了什么吗?

【问题讨论】:

    标签: mongodb nestjs


    【解决方案1】:

    findAll 返回一个数组。你告诉 Typescript 你希望返回一个对象。将您的返回类型更新为Promise&lt;Category[]&gt;,将您的查询更新为@Query(() =&gt; [Category])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      • 2022-10-13
      • 2014-11-12
      • 1970-01-01
      • 2020-06-28
      相关资源
      最近更新 更多