-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserModel.js
More file actions
108 lines (95 loc) · 2.15 KB
/
userModel.js
File metadata and controls
108 lines (95 loc) · 2.15 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const bcrypt = require('bcryptjs')
const { Schema, models, model } = require('mongoose');
// username
// email
// password
// confirmPassword
// avatar
const userSchema = new Schema({
firstName: {
type: String,
requied: true,
trim: true,
minlength: 3,
maxlength: 30
},
lastName: {
type: String,
requied: true,
trim: true,
minlength: 3,
maxlength: 30
},
username: {
type: String,
requied: true,
trim: true,
minlength: 3,
maxlength: 30
},
email: {
type: String,
unique: true,
requied: true,
trim: true,
minlength: 3,
maxlength: 30
},
password: {
type: String,
requied: true,
minlength: 4,
maxlength: 30,
select: false
},
confirmPassword: {
type: String,
requied: true,
validate: function(value) { return this.password === value }
},
avatar: {
type: String,
default: '/images/users/default.jpg'
},
coverPhoto: {
type: String,
},
likes: [{ // all the Tweets likes by this user
type: Schema.Types.ObjectId,
ref: 'Tweet',
}],
followers: [{ // all the users following this user
type: Schema.Types.ObjectId,
ref: 'User',
}],
following: [{ // this user are following other users
type: Schema.Types.ObjectId,
ref: 'User',
}],
retweets: [{
type: Schema.Types.ObjectId, // tweet._id those retweets retweeted by this user
ref: 'Tweet',
}],
}, {
timestamps: true,
toJSON: { virtuals: true }, // To show virtual fields when convert to json for response back
})
userSchema.virtual('fullName').get(function(value) {
return `${this.firstName} ${this.lastName}`
})
userSchema.pre('save', async function(next) {
if( !this.isModified('password') ) return next()
this.password = await bcrypt.hash(this.password, 10)
this.confirmPassword = undefined
next()
})
// methods. add with instance and statics. adds with Model
userSchema.methods.isPasswordValid = async (password, hashedPassword) => {
return await bcrypt.compare(password, hashedPassword)
}
// userSchema.post('find*', (next) => {
// this.fullName = `${this.firstName} ${this.lastName}`
// next()
// })
const User = models.User || model('User', userSchema)
module.exports = User