【发布时间】: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