-
Notifications
You must be signed in to change notification settings - Fork 0
/
inventory.js
91 lines (76 loc) · 1.89 KB
/
inventory.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
/**
* Created by dsmink on 28/01/2015.
*/
var mongoose = require('mongoose');
var itemSchema = mongoose.Schema({
name: String,
description: String
})
var Item = mongoose.model('Item', itemSchema);
var _ = require('lodash');
function getRecord (req, callback) {
Item.findOne({'_id':req.params.id}, function (err, item) {
if (err) {
console.error(err);
}
callback(err, err ? null : item);
});
}
exports.list = function (req, res) {
Item.find(function (err, items) {
if(err) {
console.error(err);
}
res.render('index', {items: items});
});
};
exports.show = function (req, res) {
getRecord(req, function (err, item) {
res.render('show', item);
});
};
exports.new = function (req, res) {
res.render('new');
};
exports.create = function (req, res) {
if(!req.body.name) {
res.send('Inventory item needs at least a name');
res.statusCode = 400;
} else {
var item = new Item({
name: req.body.name,
description: req.body.description
});
item.save(function (err, item) {
if(err) {
return console.error(err);
}
res.redirect('/');
});
}
};
exports.edit = function (req, res) {
getRecord(req, function (err, item) {
res.render('edit', item);
});
};
exports.update = function (req, res) {
var id = req.params.id;
Item.findByIdAndUpdate(id, {
name: req.body.name,
description: req.body.description
}, function (err, result) {
if (err) {
console.error(err);
}
res.redirect('/' + id);
});
};
exports.delete = function (req, res) {
Item.remove({'_id': req.params.id}, function (err, result){
if (err) {
console.error(err);
}
res.json({success: true});
});
};