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
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.
And like this you can use that
Your data objects suggest that
candidate
andbusiness
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 ifrole
iscandidate
orbusinessSpecific
fields ifrole
isbusiness
.An example would be: