-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuserSchema.js
67 lines (59 loc) · 1.32 KB
/
userSchema.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
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const secret_key = process.env['SECRETKEYJWT'];
const { Schema } = mongoose;
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
},
tokens: [
{
token: {
type: String,
required: true
}
}
],
});
// userSchema.pre('save', async function(next) {
// if (this.isModified('password')) {
// this.password = bcrypt.hash(this.password, 12);
// }
// console.log("This is inside!")
// next();
// });
userSchema.pre("save", async function(next) {
if (!this.isModified("password")) {
return next()
}
const salt = await bcrypt.genSalt();
this.password = await bcrypt.hashSync(this.password, salt);
next();
})
// We are generatig token
userSchema.methods.generateAuthToken = async function() {
try {
let newtoken = jwt.sign({ _id: this._id }, secret_key);
this.tokens = this.tokens.concat({ token: newtoken });
await this.save();
return newtoken;
} catch (err) {
console.log(err);
}
}
const User = mongoose.model('User', userSchema);
module.exports = User;