Kakadiya Jay
Kakadiya Jay

Reputation: 11

how can i manage different required fields for 2 type users role in a single userModel.ts file in using nextjs and mongo register API

Check this my Complete Model code and 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 and how can I save field with role based condition also I have mentioned MY API code as well please check both and give me proper updated code:

import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';
import { UserRole } from '../userRoles.enum';

const userSchema = new mongoose.Schema({

  email: {
    type: String,
    required: [true, 'Email is required'],
    maxlength: [60, 'Email must be less than 60 characters'],
    unique: true,
    match: [/^\S+@\S+\.\S+$/, 'Please provide a valid email address']
  },

  password: {
    type: String,
    required: [true, 'Password is required'],
    minlength: [6, 'Password must be at least 6 characters long'],
    validate: {
      validator: function (v:any) {
        return /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/.test(v);
      },
      message: 'Password must contain at least one letter and one number'
    }
  },

  isVerified: {
    type: Boolean,
    default: false,
  },

  role: {
    type: String,
    enum: UserRole,
    required: true,
  },

  firstName: {
    type: String,
    required: false,
  },

  lastName:{
    type: String,
    required: false,
  },

  candidateSpecific: {

    whatBroughtYouToPikle: {
      type: String,
    },
    currentStatus: {
      type: String,
    },
    idealStartDate: {
      type: Date,
    },
    industry: {
      type: String,
    },
    currentLocation: {
      type: String,
    },
    futureLocation: {
      type: String,
    },
    uniqueValueProposition: {
      type: String,
    },
    yourSkills: {
      type: [String],
    },
    problemSolvingSkills: {
      type: String,
    },
    skillsDetailDescription: {
      type: String,
    },
    careerTimeline: {
      type: [Object],
    },
  },

  businessSpecific: {
    companyName: {
      type: String,
    },
    companySize: {
      type: String,
    },
    industry: { 
      type: String,
    },
    location: {
      type: String,
    },
    uniqueValueProposition: {
      type: String,
    },
  },

  otp: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'otp',
  },

});

userSchema.pre('save', async function (next) {
  if (this.isModified('password') || this.isNew) {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
  }
  next();
});

const Users = mongoose.models.users || mongoose.model("users", userSchema);

export default Users;

API CODE

import connect from "@/app/dbConfig/dbConfig";
import Users from "@/app/models/users/userModel";
import { NextRequest, NextResponse } from 'next/server';
import OTP from "@/app/models/otp/otpModel";
import crypto from 'crypto' 
import { sendEmail } from "@/app/helpers/mailerHelper";

connect();

export async function POST(request:NextRequest){
    try {
        let reqBody;
            try {
            reqBody = await request.json();
            } catch (error) {
            console.error('Error parsing request body:', error);
            return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
            }
    const { 
      email, 
      password,
      role,
      ...otherFields  
    } = reqBody;

    if (!email || !password) {
      return NextResponse.json({ error: 'Email and password are required' }, { status: 400 });
    }
    if(!role){
      return NextResponse.json({ error: 'Role is required'},{ status:500 });
    }
    if (!Object.values(['candidate', 'business']).includes(role)) {
      return NextResponse.json({ message: 'Invalid user role' }, { status: 400 });
    }

    const existingUser = await Users.findOne({ email: { $regex: new RegExp(email, 'i') } });

    if (existingUser) {
      return NextResponse.json({ error: 'User already exists' }, { status: 400 });
    }
    
    const newUser = new Users({
        email,
        password,
        role,
        ...otherFields
      });

      try {
        const savedUser = await newUser.save();
        
        const otp = crypto.randomBytes(3).toString('hex');
        const otpExpires = new Date(Date.now() + 5 * 60 * 1000);

        const newOtp = new OTP({
            otp,
            user: savedUser._id,
            expiresAt: otpExpires
          });

        await newOtp.save();

        await sendEmail(savedUser.email, 'Verify Your Email', `Your OTP is ${otp}`);

      return NextResponse.json({
        message: 'User created successfully. Check your email for the OTP.',
        success: true,
        data: {
            id: savedUser._id,
            email: savedUser.email,
          },
      });   
      } catch (error:any) {
        if (error.name === 'ValidationError') {
            const errors = Object.values(error.errors).map(err => error.message);
            return NextResponse.json({ errors }, { status: 400 });
          } else {
            console.error(error);
            return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
          }
      } 
    } catch (error) {
        console.error(error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}

I want to fix above given code and want updated proper code.

Upvotes: 0

Views: 21

Answers (0)

Related Questions