skip to Main Content

i’m trying to create diffrent schema for single collection just like User or subUser and i want to store both User or subuser data in same collection but schema want diffrent here is my schema file

export const AryaSchema = new mongoose.Schema({
  first_name: { type: String, required: true },
  last_name: { type: String, required: true },
  userName: { type: String, unique: true, required: true },
  email: { type: String, unique: true, required: true },
  password: { type: String, required: true },
  type: {type:String,default:'subadmin'},
  adhar:{type:String, required:true},
  is_active:{type:Boolean,default:true},
  higher_education:{type:String},
  total_experience:{type:String}
  // status:{type:String,default:true}
}, { timestamps: true })

and here is my module file and i want to know how can i write used diffrent schema for single collection and store user or subuser data in same collection with diffrent schema


@Module({
    imports: [MongooseModule.forFeature([
        { name: 'Member', schema: MemberSchema },{name:'Member',schema:AryaSchema}
    ]),MemberAddressModule],
   
    providers: [ MemberService,AuthService, JwtStrategy,AryaService],
    controllers: [authController,AryaController]
})

And here is my Subuser schema file

export const MemberSchema = new mongoose.Schema({
  first_name: { type: String, required: true },
  last_name: { type: String, required: true },
  userName: { type: String, unique: true, required: true },
  email: { type: String, unique: true, required: true },
  password: { type: String, required: true },
  type: {type:String,default:'subadmin'},
  adhar:{type:String, required:true},
  is_active:{type:Boolean,default:true}
}, { timestamps: true })

2

Answers


  1. In my opinion it’s not a best practice.

    If two models properties same, You can add a field name user_type and fill it by values of ‘user’ or ‘sub_user’ to know differents.

    Or if they are two separate model you should define schema for each model.

    Note: for validate each model you can use nest js request validations to get correct data for each model. (Validate models in your request not in mongoose)

    Login or Signup to reply.
  2. Mongoose have a feature called Discriminators for that use case.

    Discriminators are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB collection.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search