add add/find query parameters in controller/routes

This commit is contained in:
Francesco Esposito 2019-02-20 09:39:54 +01:00
parent 88d8f40ee3
commit 721e72c460
2 changed files with 32 additions and 8 deletions

View File

@ -5,7 +5,8 @@ const router = express.Router();
router router
.route('/devices') .route('/devices')
.get(deviceController.index); .get(deviceController.index)
.post(deviceController.add);
router router
.route('/devices/:deviceId') .route('/devices/:deviceId')

View File

@ -1,13 +1,23 @@
const Device = require('../models/deviceModel'); const Device = require('../models/deviceModel');
function index(req, res) { function index(req, res) {
Device.get((err, devices) => { if (req.query.name) {
if (err) { console.log(req.query.name);
res.status(500).send(); Device.findOne({ name: req.query.name }, (err, device) => {
} if (!device) {
res.status(404).send();
res.json(devices); } else {
}); res.json(device);
}
});
} else {
Device.get((err, devices) => {
if (err) {
res.status(500).send();
}
res.json(devices);
});
}
} }
function view(req, res) { function view(req, res) {
@ -29,6 +39,18 @@ function update(req, res) {
}); });
} }
function add(req, res) {
const device = new Device(req.body);
device
.save()
.then((item) => {
res.status(201).json(item);
})
.catch((err) => {
res.status(500).send();
});
}
function remove(req, res) { function remove(req, res) {
Device.deleteOne({ _id: req.params.deviceId }, (err) => { Device.deleteOne({ _id: req.params.deviceId }, (err) => {
if (err) { if (err) {
@ -41,4 +63,5 @@ function remove(req, res) {
module.exports.index = index; module.exports.index = index;
module.exports.view = view; module.exports.view = view;
module.exports.update = update; module.exports.update = update;
module.exports.add = add;
module.exports.remove = remove; module.exports.remove = remove;