Why I can't reference by class name related entities in the same module?

577 Views Asked by At

My application is built with NestJS and Mongoose and I now need to specify relations between entities that are placed in the same module (User and Profile).

The official documentation shows this:

The User entity file sits in the users directory. This directory contains all files related to the UsersModule. You can decide where to keep your model files, however, we recommend creating them near their domain, in the corresponding module directory.

My folder structure look something like this:

src
│   ... 
│
│   
└───users
│   │   users.schema.ts
│   │   profiles.schema.ts
│   │   ...

And they are related like this: users.schema.ts

  @Field(() => Profile)
  @Prop({ type: Types.ObjectId, ref: Profile.name })
  profile?: Profile;

profiles.schema.ts

  @Field(() => User)
  @Prop({ type: Types.ObjectId, ref: User.name })
  customer?: User;

But, when I try to compile I got the foofliwin error:

D:\Path\to\profile.schema.ts:61
  @Prop({ type: Types.ObjectId, ref: User.name })
                                          ^
TypeError: Cannot read properties of undefined (reading 'name')

I have changed the @Prop decorator in profiles.schema.ts to the following:

  @Field(() => User)
  @Prop({ type: Types.ObjectId, ref: 'User' })
  customer?: User;

And the error dissapear... Do anyone have any explanation???

1

There are 1 best solutions below

0
On

if you want to take value from another collection you muste use virtuals like this example:

AlarmSchema.virtual('sensor', {
  ref: Sensor.name,
  localField: 'sensorId',
  foreignField: '_id',
  justOne: true,
});

and you have to use populate() function when you get elements.

Nest don't allow to put it into prop because for now don't support it.