File size: 1,550 Bytes
f4fe35f
d50360d
a99a515
39f5011
a99a515
d50360d
433085e
 
 
 
 
490d8a0
433085e
a99a515
98d83e7
433085e
 
 
 
 
490d8a0
433085e
a99a515
 
 
 
d50360d
 
433085e
f4fe35f
 
 
 
 
 
433085e
d50360d
 
f4fe35f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
484fdbc
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import mongoose, { UpdateQuery } from "mongoose";
import bcrypt from "bcrypt";
import { Role } from "@common/enums/role.enum";
import { saltrounds } from "@common/models/user.model";

const { Schema } = mongoose;

export interface IAdmin {
  name: string;
  email: string;
  password: string;
  image: String;
  gender: string;
  role: Role;
}

const AdminSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true, dropDups: true },
  password: { type: String, required: true },
  image: { type: String, default: {} },
  gender: { type: String, required: true },
  role: {
    type: String,
    enum: Role
  },
});

AdminSchema.pre("save", async function (next) {
  if (this.isModified("password")) {
    this.password = await bcrypt.hash(this.password, saltrounds);
  }
  if (this.isModified("email")) {
    this.email = this.email.toLowerCase();
  }
  next();
});

AdminSchema.pre(["updateOne", "findOneAndUpdate"], async function () {
  const data = this.getUpdate() as UpdateQuery<IAdmin>;
  if (data.password) {
    data.password = await bcrypt.hash(data.password, saltrounds);
  }
  if (data.email) {
    data.email = data.email.toLowerCase();
  }
});

// pre find make email case insensitive
AdminSchema.pre(["find", "findOne"], function () {
  const query = this.getQuery();
  if (query.email) {
    query.email = query.email.toLowerCase();
  }
});

export type AdminDocument = mongoose.Document & IAdmin;

export const Admin = mongoose.model<AdminDocument>("admins", AdminSchema);