-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathupdateCollection.js
57 lines (49 loc) · 1.4 KB
/
updateCollection.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
import { omitBy, isUndefined } from 'lodash';
import Collection from '../../models/collection';
function removeUndefined(obj) {
return omitBy(obj, isUndefined);
}
export default function createCollection(req, res) {
const { id: collectionId } = req.params;
const owner = req.user._id;
const { name, description, slug } = req.body;
const values = removeUndefined({
name,
description,
slug
});
function sendFailure({ code = 500, message = 'Something went wrong' }) {
res.status(code).json({ success: false, message });
}
function sendSuccess(collection) {
if (collection == null) {
sendFailure({
code: 404,
message: 'Not found, or you user does not own this collection'
});
return;
}
res.json(collection);
}
async function findAndUpdateCollection() {
// Only update if owner matches current user
return Collection.findOneAndUpdate({ _id: collectionId, owner }, values, {
new: true,
runValidators: true,
setDefaultsOnInsert: true
})
.populate([
{ path: 'owner', select: ['id', 'username'] },
{
path: 'items.project',
select: ['id', 'name', 'slug', 'visibility'],
populate: {
path: 'user',
select: ['username']
}
}
])
.exec();
}
return findAndUpdateCollection().then(sendSuccess).catch(sendFailure);
}