Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.3 kB
3
Indexable
Never
// Import required modules
const crypto = require('crypto');
const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');

// Define the base user schema
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Please, tell us your name!'],
    unique: true
  },
  email: {
    type: String,
    required: [true, 'Please provide your email!'],
    unique: true,
    lowercase: true,
    validate: [validator.default.isEmail, 'Please provide a valid email address!']
  },
  phone: {
    type: String,
    required: [true, 'Please type your phone!']
  },
  password: {
    type: String,
    required: [true, 'Please provide a password'],
    minlength: 8,
    select: false
  },
  passwordConfirm: {
    type: String,
    required: [true, 'Please confirm your password'],
    validate: {
      validator: function(el) { return el === this.password; },
      message: 'Passwords are not the same'
    }
  },
  passwordChangedAt: Date,
  passwordResetToken: String,
  passwordResetExpires: Date,
  profileImage: {
    type: String,
    default: 'default.jpg'
  },
  role: {
    type: String,
    required: true,
    enum: ['admin', 'partner', 'owner', 'agent']
  },
  active: {
    type: Boolean,
    default: false,
    select: false
  }
}, {
  discriminatorKey: 'role',
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Define methods and pre-save hooks as shown previously...

// Create the base User model
const User = mongoose.model('User', userSchema);

// Create a discriminator for the 'Agent' role
const Agent = User.discriminator('Agent', new mongoose.Schema({
  commissionRate: { type: Number, required: true },
  salesTarget: { type: Number, required: true }
}));

// Create other discriminators similarly...
const Admin = User.discriminator('Admin', new mongoose.Schema({
  accessLevel: { type: Number, required: true }
}));

const Partner = User.discriminator('Partner', new mongoose.Schema({
  partnershipDate: { type: Date, required: true }
}));

// Export the base User model and discriminators if needed
module.exports = { User, Admin, Agent, Partner };
Leave a Comment