forked from gdscpce/hacktober-codesnippet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongooseModel.js
68 lines (60 loc) · 1.52 KB
/
mongooseModel.js
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
61
62
63
64
65
66
67
68
import mongoose, { Schema } from "mongoose";
import validator from "validator";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import crypto from "crypto";
const schema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Please enter your name"],
},
email: {
type: String,
required: [true, "Please enter your email"],
validate: validator.isEmail,
},
password: {
type: String,
required: true,
select: false,
minlength: 8,
},
refreshToken: [
{
type: String,
},
],
resetPasswordToken: String,
resetPasswordExpire: String,
deleted: {
type: Boolean,
default: false,
},
},
{
timestamps: true,
}
);
schema.pre("save", async function (next) {
if (!this.isModified("password")) return next();
this.password = await bcrypt.hash(this.password, 10);
});
schema.methods.comparePassword = async function (password) {
return await bcrypt.compare(password, this.password);
};
schema.methods.getJWTToken = function () {
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRE,
});
};
schema.methods.getResetToken = async function () {
const resetToken = crypto.randomBytes(20).toString("hex");
this.resetPasswordToken = crypto
.createHash("sha256")
.update(resetToken)
.digest("hex");
this.resetPasswordExpire = Date.now() + 50 * 60 * 1000;
return resetToken;
};
export const Model = mongoose.model("model", schema);