-
Notifications
You must be signed in to change notification settings - Fork 0
/
User.js
46 lines (40 loc) · 1.22 KB
/
User.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
const mongoose = require('mongoose');
const { isEmail } = require('validator');
const bycrypt = require('bcrypt');
const userSchema = new mongoose.Schema({
email: {
type: String,
required: [true, 'Please enter an email'],
unique: true,
lowercase: true,
validate: [isEmail, 'Please enter a valid email']
},
password: {
type: String,
required: [true, 'Please enter a password'],
minlength: [6, 'Minimum password length is 6 characters'],
}
});
// fire a function after doc saveed to db
userSchema.post('save', function(doc, next){
console.log('new user created &saved');
next()
})
// fire a function before doc saved to db in order to hash the password
userSchema.pre('save', async function(next){
const salt = await bycrypt.genSalt();
this.password = await bycrypt.hash(this.password, salt);
next();
})
//static method to login user
userSchema.statics.login = async function(email, password){
const user = await this.findOne({email});
if(user){
const auth = await bycrypt.compare(password, user.password);
if(auth){
return user;
}throw Error('incorrect password');
}throw Error('incorrect email');
}
const User = mongoose.model('user', userSchema);
module.exports = User;