-
Notifications
You must be signed in to change notification settings - Fork 2
/
workoutsController.js
60 lines (50 loc) · 1.59 KB
/
workoutsController.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
const db = require("../models/");
const moment = require('moment')
module.exports = {
//----[api/workouts/]
//query for all workouts in collection
findAll: function(req, res) {
db.Workouts
.find(req.query)
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
//create a workout
create: function(req, res) {
db.Workouts
.create({})
.then(dbModel =>
{
db.Workouts.updateOne({_id: dbModel._id}, {workout: req.body, created: moment()})
.then(results => {
db.Users.updateOne({_id: req.user._id}, {$push: {savedWorkouts: dbModel._id}})
.then(r => res.json(r))
})
})
.catch(err => res.status(422).json(err));
},
//-----[api/workouts/:id]
//query for a workout with a specific id
findById: function(req, res) {
db.Workouts
.findById(req.params.id)
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
//update a workout with a specific id
update: function(req, res) {
db.Workouts
.findOneAndUpdate({ _id: req.params.id }, req.body)
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
//remove a workout with a specific id
remove: function(req, res) {
db.Workouts
.deleteOne({ _id: req.params.id })
.then(() => db.Users.updateOne({ _id: req.user._id}, {$pull: { savedWorkouts: {$in: [ req.params.id ]}}})
.then(model => res.json(model.savedWorkouts))
)
.catch(err => res.status(422).json(err));
}
};