|
1 | 1 | const moment = require('moment'); |
2 | | -const mongoosePaginate = require('mongoose-paginate'); |
3 | 2 | const bcrypt = require('bcryptjs'); |
4 | 3 | const uniqueValidator = require('mongoose-unique-validator'); |
5 | | - |
6 | | -function create(mongoose) { |
7 | | - const userSchema = mongoose.Schema({ |
8 | | - name: { |
9 | | - type: String, |
10 | | - required: true, |
11 | | - }, |
12 | | - surname: { |
13 | | - type: String, |
14 | | - required: true, |
15 | | - }, |
16 | | - username: { |
17 | | - type: String, |
18 | | - required: true, |
19 | | - }, |
20 | | - password: { |
21 | | - type: String, |
22 | | - required: true, |
23 | | - }, |
24 | | - email: { |
25 | | - type: String, |
26 | | - required: true, |
27 | | - unique: true, |
28 | | - }, |
29 | | - created: Date, |
30 | | - }); |
31 | | - |
32 | | - userSchema.pre('save', function (next) { |
33 | | - bcrypt.genSalt(10, (err, salt) => { |
34 | | - if (err) { |
35 | | - return next(err); |
| 4 | +const { |
| 5 | + model, |
| 6 | + Schema, |
| 7 | +} = require('mongoose'); |
| 8 | + |
| 9 | +const UserSchema = new Schema({ |
| 10 | + name: { |
| 11 | + type: String, |
| 12 | + required: true, |
| 13 | + }, |
| 14 | + surname: { |
| 15 | + type: String, |
| 16 | + required: true, |
| 17 | + }, |
| 18 | + username: { |
| 19 | + type: String, |
| 20 | + required: true, |
| 21 | + }, |
| 22 | + password: { |
| 23 | + type: String, |
| 24 | + required: true, |
| 25 | + }, |
| 26 | + email: { |
| 27 | + type: String, |
| 28 | + required: true, |
| 29 | + unique: true, |
| 30 | + }, |
| 31 | + created: Date, |
| 32 | +}); |
| 33 | + |
| 34 | +UserSchema.index({ name: 1 }); |
| 35 | + |
| 36 | +UserSchema.index({ name: 1, created: -1 }); |
| 37 | + |
| 38 | +UserSchema.plugin(uniqueValidator); |
| 39 | + |
| 40 | +UserSchema.pre('save', function (next) { |
| 41 | + bcrypt.genSalt(10, (err, salt) => { |
| 42 | + if (err) { |
| 43 | + return next(err); |
| 44 | + } |
| 45 | + bcrypt.hash(this.password, salt, (error, hash) => { |
| 46 | + if (error) { |
| 47 | + return next(error); |
36 | 48 | } |
37 | | - bcrypt.hash(this.password, salt, (err, hash) => { |
38 | | - if (err) { |
39 | | - return next(err); |
40 | | - } |
41 | | - this.password = hash; |
42 | | - this.created = moment().toJSON(); |
43 | | - return next(); |
44 | | - }); |
| 49 | + this.password = hash; |
| 50 | + this.created = moment().toJSON(); |
| 51 | + return next(); |
45 | 52 | }); |
46 | 53 | }); |
| 54 | +}); |
47 | 55 |
|
48 | | - userSchema.index({ name: 1 }); |
49 | | - |
50 | | - userSchema.index({ name: 1, created: -1 }); |
51 | | - |
52 | | - userSchema.plugin(mongoosePaginate); |
53 | | - |
54 | | - userSchema.plugin(uniqueValidator); |
55 | | - |
56 | | - return mongoose.model('User', userSchema); |
57 | | -} |
58 | | - |
| 56 | +const UserDao = model('User', UserSchema); |
59 | 57 |
|
60 | | -module.exports = create; |
| 58 | +module.exports = { UserDao }; |
0 commit comments