-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathcreate.js
91 lines (82 loc) · 2.15 KB
/
create.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
const mongoose = require('mongoose');
const People = mongoose.model('People');
const Company = mongoose.model('Company');
const create = async (Model, req, res) => {
// Creating a new document in the collection
if (req.body.type === 'people') {
if (!req.body.people) {
return res.status(403).json({
success: false,
message: 'Please select a people',
});
} else {
let client = await Model.findOne({
people: req.body.people,
removed: false,
});
if (client) {
return res.status(403).json({
success: false,
result: null,
message: 'Client Already Exist',
});
}
let { firstname, lastname } = await People.findOneAndUpdate(
{
_id: req.body.people,
removed: false,
},
{ isClient: true },
{
new: true, // return the new result instead of the old one
runValidators: true,
}
).exec();
req.body.name = firstname + ' ' + lastname;
req.body.company = undefined;
}
} else {
if (!req.body.company) {
return res.status(403).json({
success: false,
message: 'Please select a company',
});
} else {
let client = await Model.findOne({
company: req.body.company,
removed: false,
});
if (client) {
return res.status(403).json({
success: false,
result: null,
message: 'Client Already Exist',
});
}
let { name } = await Company.findOneAndUpdate(
{
_id: req.body.company,
removed: false,
},
{ isClient: true },
{
new: true, // return the new result instead of the old one
runValidators: true,
}
).exec();
req.body.name = name;
req.body.people = undefined;
}
}
req.body.removed = false;
const result = await new Model({
...req.body,
}).save();
// Returning successfull response
return res.status(200).json({
success: true,
result,
message: 'Successfully Created the document in Model ',
});
};
module.exports = create;