-
Notifications
You must be signed in to change notification settings - Fork 0
/
group.model.js
68 lines (62 loc) · 1.3 KB
/
group.model.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
const mongoose = require('mongoose');
const { toJSON, paginate } = require('./plugins');
const groupSchema = mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true,
},
description: {
type: String,
required: true,
trim: true,
},
private: {
type: Boolean,
required: true,
},
image: {
type: String,
},
admin: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
members: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
],
},
{
timestamps: true,
}
);
groupSchema.methods.addUser = function (user) {
const userId = user._id;
if (!this.members.includes(userId)) {
this.members.push(userId);
return this.save();
}
return this;
};
groupSchema.methods.deleteUser = function (user) {
const userId = user._id;
const index = this.members.findIndex((item) => item.toHexString() === userId.toHexString());
if (index !== -1) {
this.members.splice(index, 1);
return this.save();
}
return this;
};
// add plugin that converts mongoose to json
groupSchema.plugin(toJSON);
groupSchema.plugin(paginate);
/**
* @typedef User
*/
const Group = mongoose.model('Group', groupSchema);
module.exports = Group;