-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUser.js
124 lines (107 loc) · 2.82 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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
const mongoose = require('mongoose');
/* practice of mongoose outer schema for another schema */
const adressSchema = new mongoose.Schema({
street: {
type: String,
validate:{
validator: function(v){
return v.length > 0;
},
message: 'Street must be longer than 1 character'
}
},
city: String,
})
/* actual schema */
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 1,
trim: true,
validate: {
validator: function(v){
return v.length > 0;
},
message: 'Name must be longer than 1 character'
}
},
completed: {
type: Boolean,
default: false
},
age: {
type: Number,
min: 0,
max: 101,
validate: {
validator: function(v){
return 101 > v > 0;
},
message: 'Age must be between 0 and 101'
}
},
bestFriend: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'User',
validate:{
validator: function(v){
return v != this._id;
},
message: 'Best friend must be different from user'
}
},
hobbies: {
type: [String],
default: ['reading', 'writing', 'coding'],
validate: {
validator: function(v){
return v.length > 0;
},
message: 'A user must have at least one hobby'
}
},
adress: adressSchema,
createdAt: {
type: Date,
default: () => Date.now(),
immutable: true ,/* makes date unchangable to keep exact track. */
},
updatedAt: {
type: Date,
default: () => Date.now()
}
});
/* practice of methods */
userSchema.methods.myBestFriend = async function getBestFriend(){
try{
const user = await this.populate('bestFriend');
console.log( `${this.bestFriend.name} is my best friend`);
}catch(e){
console.log(e);
}
}
/* practice of statics */
userSchema.statics.findOneByName = function findByName(name){
return this.find({name: new RegExp(name, 'i')}).limit(1);
}
/* practice of queries */
userSchema.query.byName = function findByName(name){
return this.where({name: new RegExp(name, 'i')}).limit(1);
}
/* practice of virtuals */
userSchema.virtual('fullName').get(function(){
return `${this.name}dasdds`;
})
/* practice of pre middleware */
userSchema.pre('save', function(next){
this.updatedAt = Date.now();
this.createdAt = Date.now();
next();
})
/* practice of post middleware */
userSchema.post('save', function(doc, next){
console.log('Saved', doc);
next();
})
module.exports= mongoose.model('User', userSchema);