【问题标题】:Mongoose Schema is undefinedMongoose Schema 未定义
【发布时间】:2021-03-22 07:27:17
【问题描述】:

我有 2 个模式:用户和产品,用户有产品数组,产品有单个用户。架构看起来像:

用户:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Schema as mongooseSchema } from 'mongoose';

import { Product } from '../product/product.schema';

export type UserDocument = User & Document;

@Schema()
export class User {
  @Prop()
  username: string;

  @Prop({ type: [{ type: mongooseSchema.Types.ObjectId, ref: Product }] })
  product: Product[];
}

export const UserSchema = SchemaFactory.createForClass(User);

产品:

import { Document, Schema as mongooseSchema } from 'mongoose';
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { User } from '../user/user.schema';

export type ProductDocument = Product & Document;

@Schema()
export class Product {
  @Prop()
  name: string;

  @Prop({ type: mongooseSchema.Types.ObjectId, ref: User })
  user: User;
}

export const ProductSchema = SchemaFactory.createForClass(Product);

产品模块:

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: User.name, schema: UserSchema },
      { name: Product.name, schema: ProductSchema },
    ]),
    UserModule,
  ],
  providers: [ProductService],
  controllers: [ProductController],
})
export class ProductModule {}

问题出现在编译时: TypeError:无法读取 product.schema.js:25 中未定义的属性“名称”

我认为存在一些异步问题,当我尝试初始化用户模型时,它会看到产品模型的引用并开始初始化产品模型,但随后产品模型将引用指向尚未初始化的用户模型。如果我删除产品:用户模型中的 Product[] 编译成功

如何避免这个编译时错误,非常感谢!

【问题讨论】:

  • 在产品架构中是:从'../user/user.schema'导入{用户};并且在产品模块中 UserModule 也被导入
  • 嗯,这实际上看起来不错(您之前使用 Product.name 的方式实际上是正确的,我错了) - 很奇怪,我会尝试重现这个。
  • 是的,我认为应该有办法在 ref 模型上进行异步加载,但不确定

标签: node.js mongodb mongoose nestjs


【解决方案1】:

虽然我不能 100% 确定,但您可以尝试将 ref 值指定为字符串,而不是使用类的 name 属性。循环依赖可能存在一些问题:

@Schema()
export class Product {
  @Prop()
  name: string;

  @Prop({ type: mongooseSchema.Types.ObjectId, ref: 'User'})
  user: User;
}

编辑: 刚刚在 github 上获得了 feedback:在处理架构中的循环 deps 时,必须使用上述字符串。

【讨论】:

  • 所以我必须创建一个结合两个参考的新模式?我可以在我的用户架构中引用产品并在我的产品架构中引用用户吗?
  • 我明白了,但问题是我的用户未定义,MongooseError: Invalid ref at path "user"。如果我只使用没有名称的用户,则会得到未定义
  • 看起来您的导入有问题。路径是否正确?
  • 我认为存在一些异步问题,当我尝试初始化用户模型时,它看到有一个产品模型的引用并开始初始化产品模型,但随后产品模型指向用户模型,这不是尚未初始化
  • 你在 github 上找到问题会很棒:)
猜你喜欢
  • 2011-11-21
  • 1970-01-01
  • 2018-03-15
  • 2014-05-29
  • 2021-09-10
  • 1970-01-01
  • 2015-05-28
  • 2019-10-03
  • 2015-01-05
相关资源
最近更新 更多