-
Notifications
You must be signed in to change notification settings - Fork 2
/
user.js
78 lines (64 loc) · 1.94 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
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
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const userRatingSchema = new mongoose.Schema({
rating: { type: Number },
user: { type: mongoose.Schema.ObjectId, ref: 'User' }
})
const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
profilePicture: { type: String },
email: { type: String, required: true, unique: true },
password: { type: String, required: true, unique: true },
libraryName: { type: String, required: true, unique: true },
location: {
lat: { type: Number, required: true },
lng: { type: Number, required: true }
},
libraryPicture: { type: String },
libraryDescription: { type: String },
userRating: [ userRatingSchema ]
}, {
timestamps: true
})
userSchema.virtual('booksOwned', {
ref: 'Book',
localField: '_id',
foreignField: 'owner'
})
userSchema.virtual('booksBorrowed', {
ref: 'Loan',
localField: '_id',
foreignField: 'borrower'
})
userSchema.set('toJSON', {
virtuals: true
})
userSchema.plugin(require('mongoose-unique-validator'))
userSchema.set('toJSON', {
transform(doc, json) {
delete json.password
return json
}
})
userSchema.methods.validatePassword = function validatePassword(password) {
return bcrypt.compareSync(password, this.password)
}
userSchema
.virtual('passwordConfirmation')
.set(function setPasswordConfirmation(passwordConfirmation){
this._passwordConfirmation = passwordConfirmation
})
userSchema.pre('validate', function checkPassword(next) {
if (this.isModified('password') && this._passwordConfirmation !== this.password) {
this.invalidate('passwordConfirmation', 'does not match')
}
next()
})
userSchema.pre('save', function hashPassword(next) {
if (this.isModified('password')) {
this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync(8))
}
next()
})
userSchema.plugin(require('mongoose-unique-validator'))
module.exports = mongoose.model('User', userSchema)