Skip to content

Commit 91c532c

Browse files
committed
add create an item or update existing item
1 parent c6b6fa6 commit 91c532c

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

item/ItemController.js

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,17 @@ module.exports = router;
88

99
// Create an item or update existing item
1010
router.post('/', (req, res) => {
11-
Item.create({
12-
key: req.body.key,
13-
value: req.body.value
14-
},
15-
(err, item) => {
16-
if (err) return res.status(500).send("error");
11+
var query = { 'key': req.body.key };
12+
var update = {
13+
value: req.body.value,
14+
timestamp: Math.floor(Date.now() / 1000)
15+
};
16+
var options = {
17+
upsert: true,
18+
new: true
19+
}
20+
Item.findOneAndUpdate(query, update, options, (err, item) => {
21+
if (err) return res.status(500).send('error');
1722
res.status(200).send(item);
1823
});
1924
});
@@ -34,7 +39,9 @@ router.get('/:key', (req, res) => {
3439
if (item.length === 0) return res.status(404).send('not found');
3540
res.status(200).send('value: ' + item[0].value)
3641
});
37-
} else {
42+
}
43+
// Get the latest value accroding to key when no timestamp query string is given
44+
else {
3845
Item.find({ 'key': req.params.key }).
3946
sort({ 'timestamp': -1 }).
4047
exec((err, item) => {

0 commit comments

Comments
 (0)