-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathUser.js
More file actions
44 lines (37 loc) · 885 Bytes
/
User.js
File metadata and controls
44 lines (37 loc) · 885 Bytes
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
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
},
googleId: {
type: String,
unique: true,
sparse: true,
},
});
UserSchema.pre('save', async function (next) {
if (!this.isModified('password'))
return next();
try {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
next();
} catch (err) {
return next(err);
}
});
// Compare passwords during login
UserSchema.methods.comparePassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
module.exports = mongoose.model("User", UserSchema);