discriminators/ single-collection-inheritance with nestjs/mongoose

Viewed 1188

The problem

Hi, I'm trying to create users collection in mongo with nestjs. I want to have couple of schemes that will inherit from one base schema, and have a basic service that can be extended.

Because nestjs/mongoose don't have such a feature I tried to implement it by myself and the main problem is that The unique key I defined is not being unique in the collection

some code

Over here I'm defining the two schemes

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

export type UserDocument = User & Document;

@Schema()
export class User {
    @Prop({ unique: true, type: 'string' })
    username: string;

    @Prop()
    password: string;

    @Prop()
    created: Date;

    @Prop()
    updated: Date;

    @Prop()
    type: string;

    @Prop()
    name?: string

    // roles: Role[];
}

export const UserSchema = SchemaFactory.createForClass(User);


@Schema()
export class EUser extends User {
    @Prop()
    language: string;
}

export const EUserSchema = SchemaFactory.createForClass(EUser);
export type EUserDocument = EUser & Document;

No in order to save them into the same collection I'm configuring the mongooseModule.forfeature to use the followings:


@Module({
  imports: [MongooseModule.forFeature([
    {
      name: EUser.name, schema: EUserSchema, collection: 'users'
    }
  ])
  ]})

So it saves everything to the same collection, but don't care (and don't even create!) about the unique index.

What i have in my db.

1 Answers

I found this function that load the indexes in the service

constructor(@InjectModel(User.name) protected UserModel: Model<UserDocument>) {

   this.UserModel.createIndexes()
}

Problem solved :)

Related