-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathUsers.js
58 lines (54 loc) · 1.37 KB
/
Users.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
const mongoose = require("mongoose");
const { isEmail } = require("validator");
const bcrypt = require("bcryptjs");
const uniqueValidator = require("mongoose-unique-validator");
const userSchema = new mongoose.Schema(
{
name: {
type: String,
unique: true,
required: [true, "Please enter a username"],
},
email: {
type: String,
required: [true, "Please enter an email id"],
unique: true,
validate: [isEmail, "Please enter a valid email"],
},
password: {
type: String,
required: [true, "Password length must be atleast 6 characters"],
minlength: [6, "Password length must be atleast 6 characters"],
},
answers: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Answer",
},
],
questions: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Question",
},
],
},
{
timestamps: true,
}
);
userSchema.plugin(uniqueValidator);
userSchema.pre("save", async function (next) {
// console.log("inside changing password");
const salt = await bcrypt.genSalt();
this.password = await bcrypt.hash(this.password, salt);
next();
});
userSchema.methods.comparePasswords = function (userPassword, callback) {
bcrypt.compare(userPassword, this.password, function (error, isMatch) {
if (error) return callback(error);
return callback(null, isMatch);
});
};
const User = mongoose.model("User", userSchema);
module.exports = User;