这是我的代码,正确吗?或者给我最好的建议。我有两种类型的用户角色,例如候选人和业务,并且都有多个不同的字段,我想管理一个 userModel.ts 文件中的所有字段。
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);
是的,但是您可以进行一些改进,以更有效地处理每个角色的特定字段。您可以将 Mongoose 的混合类型用于特定于每个角色的字段,并确保它们仅根据用户的角色是必需的或存在。
并且不要忘记使用 pre 方法来指定角色。
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);
像这样你可以使用它
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',
},
});