forked from makinhs/rest-api-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusers.model.js
More file actions
89 lines (76 loc) · 2.04 KB
/
users.model.js
File metadata and controls
89 lines (76 loc) · 2.04 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
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/rest-tutorial');
const Schema = mongoose.Schema;
const userSchema = new Schema({
firstName: String,
lastName: String,
email: String,
password: String,
permissionLevel: Number
});
userSchema.virtual('id').get(function () {
return this._id.toHexString();
});
// Ensure virtual fields are serialised.
userSchema.set('toJSON', {
virtuals: true
});
userSchema.findById = function (cb) {
return this.model('Users').find({id: this.id}, cb);
};
const User = mongoose.model('Users', userSchema);
exports.findByEmail = (email) => {
return User.find({email: email});
};
exports.findById = (id) => {
return User.findById(id)
.then((result) => {
result = result.toJSON();
delete result._id;
delete result.__v;
return result;
});
};
exports.createUser = (userData) => {
const user = new User(userData);
return user.save();
};
exports.list = (perPage, page) => {
return new Promise((resolve, reject) => {
User.find()
.limit(perPage)
.skip(perPage * page)
.exec(function (err, users) {
if (err) {
reject(err);
} else {
resolve(users);
}
})
});
};
exports.patchUser = (id, userData) => {
return new Promise((resolve, reject) => {
User.findById(id, function (err, user) {
if (err) reject(err);
for (let i in userData) {
user[i] = userData[i];
}
user.save(function (err, updatedUser) {
if (err) return reject(err);
resolve(updatedUser);
});
});
})
};
exports.removeById = (userId) => {
return new Promise((resolve, reject) => {
User.remove({_id: userId}, (err) => {
if (err) {
reject(err);
} else {
resolve(err);
}
});
});
};