【问题标题】:Reference another model in mongoose schema using Nest.js使用 Nest.js 在猫鼬模式中引用另一个模型
【发布时间】:2021-08-17 18:18:27
【问题描述】:

我刚开始使用 Nest.js,我无法理解为什么我不能在其他 mongoose 架构中引用 mongoose 模型。

它适用于 Unit 模型,但不适用于 Product。

这是我的参考代码:

ProductUnit 架构

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, SchemaTypes } from 'mongoose';
import { Product } from 'src/products/entities/product.entity';
import { Unit } from 'src/units/entities/unit.entity';

@Schema()
export class ProductUnit extends Document {
  @Prop({ type: SchemaTypes.ObjectId, ref: Unit.name })
  unit: Unit;

  @Prop({ type: SchemaTypes.ObjectId, ref: Product.name })
  product: Product;

  @Prop({ default: false })
  defaultBuy: boolean;

  @Prop({ default: false })
  defaultSell: boolean;
}

export const ProductUnitSchema = SchemaFactory.createForClass(ProductUnit);

产品单元模块

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ProductsModule } from 'src/products/products.module';
import { UnitsModule } from 'src/units/units.module';
import { ProductUnit, ProductUnitSchema } from './entities/product-unit.entity';
import { ProductUnitsService } from './product-units.service';

@Module({
  imports: [
    MongooseModule.forFeature([
      {
        name: ProductUnit.name,
        schema: ProductUnitSchema,
      },
    ]),
    UnitsModule,
    ProductsModule,
  ],
  providers: [ProductUnitsService],
  exports: [ProductUnitsService],
})
export class ProductUnitsModule {}

产品模块

@Module({
  imports: [
    MongooseModule.forFeature([
      {
        name: Product.name,
        schema: ProductSchema,
      },
    ]),
    TagsModule,
    ProductUnitsModule,
  ],
  controllers: [ProductsController],
  providers: [
    ProductsService,
    IsTagValidator,
    IsCategoryValidator,
    ProductUnitsService,
  ],
  exports: [ProductsService],
})
export class ProductsModule {}

当我尝试运行我的应用程序时出现以下错误:

/mnt/c/Users/***/Documents/codespace/FullPOS/fullpos/dist/products/entities/product.entity.js:41
    mongoose_1.Prop({ type: [{ type: mongoose_2.SchemaTypes.ObjectId, ref: product_unit_entity_1.ProductUnit.name }] }),

TypeError: Cannot read property 'name' of undefined
    at Object.<anonymous> (/mnt/c/Users/***/Documents/codespace/FullPOS/fullpos/dist/products/entities/product.entity.js:41:110)        
    at Module._compile (node:internal/modules/cjs/loader:1108:14)

这让我措手不及,因为我正在对其他 mongoose 模式做同样的事情,而且效果很好。

感谢您的帮助。

【问题讨论】:

    标签: mongoose nestjs


    【解决方案1】:

    我也在处理同样的问题。我通过将架构(集合)名称作为字符串传递来解决它,例如 ref: 'Product' 而不是 ref: Product.name

    我知道这个解决方案在这里会影响类型安全,但这似乎是唯一的解决方案。其他人有更好的解决方案吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-01
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 2023-03-18
      • 2015-05-15
      • 1970-01-01
      相关资源
      最近更新 更多