skip to Main Content

Here is my code is it correct? Or give me best suggestion. I have two type user role like candidate and business and both have multiple different fields and I want to manage all the fields in one userModel.ts file.

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  role: {
    type: String,
    enum: ['candidate', 'business'],
    required: true,
  },
  // ... Other common fields applicable to both roles
  // Define optional fields specific to each role (if any)
  candidateSpecific?: {
    // Candidate-specific fields (optional)
  },
  businessSpecific?: {
    // Business-specific fields (optional)
  },
});

export default mongoose.models.users || mongoose.model('users', userSchema);

2

Answers


  1. Yes, but there are a few improvements you can make to handle the specific fields for each role more effectively. You can use Mongoose’s mixed type for the fields specific to each role and ensure that they are only required or present depending on the user’s role.

    and do not forgot to user pre method to specify role.

    import mongoose, { Schema, Document } from 'mongoose';
    
    interface IUser extends Document {
      email: string;
      password: string;
      role: 'candidate' | 'business';
      candidateSpecific?: {
        // Define candidate-specific fields here
        resume?: string;
        portfolio?: string;
      };
      businessSpecific?: {
        // Define business-specific fields here
        companyName?: string;
        companyWebsite?: string;
      };
    }
    
    const userSchema = new Schema<IUser>({
      email: {
        type: String,
        required: true,
        unique: true,
      },
      password: {
        type: String,
        required: true,
      },
      role: {
        type: String,
        enum: ['candidate', 'business'],
        required: true,
      },
      candidateSpecific: {
        type: Schema.Types.Mixed,
        default: {},
      },
      businessSpecific: {
        type: Schema.Types.Mixed,
        default: {},
      },
    });
    
    userSchema.pre('save', function (next) {
      const user = this as IUser;
    
      if (user.role === 'candidate') {
        user.businessSpecific = undefined;
      } else if (user.role === 'business') {
        user.candidateSpecific = undefined;
      }
    
      next();
    });
    
    export default mongoose.models.User || mongoose.model<IUser>('User', userSchema);

    And like this you can use that

     const newUser = new User({
        email: '[email protected]',
        password: 'securepassword',
        role: 'candidate',
        candidateSpecific: {
          resume: 'link_to_resume',
          portfolio: 'link_to_portfolio',
        },
      });
      
      
       const newUser = new User({
        email: '[email protected]',
        password: 'securepassword',
        role: 'business',
        businessSpecific: {
          companyName: 'Company Inc.',
          companyWebsite: 'https://company.com',
        },
      });
    Login or Signup to reply.
  2. Your data objects suggest that candidate and business specific fields should be handled with separate models.

    However, since you want to handle all data in one model you can use Subdocuments and pass a function to the required validator to ensure that candidateSpecific fields are included if role is candidate or businessSpecific fields if role is business.

    An example would be:

    import mongoose from 'mongoose';
    
    // Create a schema for candidate. This will not add a new collection or model
    const candidateSchema = new mongoose.Schema({
        whatBroughtYouToPikle: {
            type: String,
        },
        currentStatus: {
            type: String,
        },
        //...
    });
    
    // Create a schema for business. This will not add a new collection or model
    const businessSchema = new mongoose.Schema({
        companyName: {
            type: String,
        },
        companySize: {
            type: String,
        },
        //...
    });
    
    const userSchema = new mongoose.Schema({
        email: {
            type: String,
            required: true,
            unique: true,
        },
        password: {
            type: String,
            required: true,
        },
        role: {
            type: String,
            enum: ['candidate', 'business'],
            required: true,
        },
        // ... 
        candidateSpecific:{
            type: candidateSchema,
            required: function (){
                return this.role === "candidate";
            }
        },
        businessSpecific: {
            type: businessSchema,
            required: function (){
                return this.role === "business";
            }
        },
    });
    
    export default mongoose.models.User || mongoose.model<IUser>('User', userSchema);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search