nestjs / mongoose

Mongoose module for Nest framework (node.js) 🍸
https://nestjs.com
MIT License
528 stars 118 forks source link

How to initialize ref lazily #693

Closed AndonMitev closed 3 years ago

AndonMitev commented 3 years ago

I have 2 schemas: User and Product, User have array of products and Product have single user. Schemas looks like:

User:

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

Product:

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

Product module:

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

Issue come on compile time: TypeError: Cannot read property 'name' of undefined in product.schema.js:25

I think there is some async issue, When i try to initialize User Model it sees there a ref to Product model and goes to initialize Product model, but then product model point ref to user model which is not initialized yet. If I remove product: Product[] from User Model compiles successfully

How I'm able to avoid this compile time error, thanks a lot!

kamilmysliwiec commented 3 years ago

You can change "ref: User" to "ref: 'User'" (that's actually what ".name" expression gives you as well)