首页 > 解决方案 > Typescript mongoose - 我的数组中未定义的对象

问题描述

我不明白为什么我的 Promise 没有实现,如果我理解的话:从我的 mongodb 文档创建的对象应该填充我的数组,在这里它给出一个未定义的对象,所以我的对象是空的,对吗?

product.resolver.ts

import { Resolver, Query, Arg, Int, ObjectType, Mutation } from 'type-graphql';
import { Product, ProductModel, ProductResponse } from './product.type';
import { filterItems, getRelatedItems } from '../../helpers/filter';
import { createProductSamples } from './product.sample';

@Resolver()
export class ProductResolver {
  private readonly items: Product[] = createProductSamples();

  @Query(() => Product)
  async product(
    @Arg('slug', (type) => String) slug: string
  ): Promise<Product | undefined> {
    return await this.items.find((item) => item.slug === slug);
  }

}

产品.sample.ts

这是从 mongodb 获取数据并用文档对象填充我的数组的函数

import { Product, ProductModel }  from './product.type';
import { plainToClass } from 'class-transformer';
import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';

export function createProductSamples() {
  //const inventory = useQuery<InventoryData>(GetInventory);
  const data = ProductModel.find();
  console.log(data);
  return plainToClass(Product, [data]);

}

产品类型.ts

这是相关的类

@ObjectType()
export class Product {

  @Field()
  @Property()
  id: number;

  @Field()
  @Property()
  slug: string;

  @Field()
  @Property()
  title: string;

  @Field(() => ProductType)
  @Property()
  type: ProductType;

  @Field(() => [Category])
  @Property()
  categories: Category[];

  @Field()
  @Property()
  unit: string;

  @Field()
  @Property()
  image: string;

  @Field(() => [Gallery])
  @Property()
  gallery: Gallery[];

  @Field()
  @Property()
  description: string;

  @Field()
  @Property()
  price: number;

  @Field()
  @Property()
  salePrice: number;

  @Field()
  @Property()
  discountInPercent: number;

  @Field(() => Author, { nullable: true })
  @Property()
  author?: Author;

  @Field(() => Meta, { nullable: true })
  @Property()
  meta?: Meta;

  @Field()
  @Property()
  createdAt: Date;
}

输出图Ql

{
  "errors": [
    {
      "message": "Cannot read property 'Promise' of undefined",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "product"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "TypeError: Cannot read property 'Promise' of undefined",
            "    at new NativeCollection ............................
            ...............................
          ]
        }
      }
    }
  ],
  "data": null
}

标签: javascriptarraysmongodbtypescriptmongoose

解决方案


推荐阅读