Creating an API for various different displays. Would like to retrieve all the displays in the database and then pass custom query strings to then filter down further. Been researching all day on how to do this and nothing has made complete sense or wasn't able to get it to work completely as expected.
A Sample URL: localhost:3000/api/v1/displays?hdmi=true&hdmi_version=1.2. In theory these custom queries could range from all different specifications displays have that include different values (strings, booleans, and integers).
Technologies
- Express: 4.13.4
- Node: 5.6.0
- MongoDB (local): 3.2.4
- Angular: 1.5, will be eventual front end but just trying to build the API and use POSTman
Database:
[
{
"_id": "572be4122847a355994a07d9",
"series": "meh-monitor",
"hdmi": false,
"hdmi_version": "",
"vga": true,
"resolution": "1366x768"
},
{
"_id": "572be4122847a355994a07da",
"series": "ok-monitor",
"hdmi": true,
"hdmi_version": "1.0",
"vga": true,
"resolution": "1920x1080"
},
{
"_id": "572be4122847a355994a07db",
"series": "good-monitor",
"hdmi": true,
"hdmi_version": "1.2",
"vga": false,
"resolution": "2560x1440"
}
]
Express - server.js
var express = require('express');
var app = express();
var path = require('path');
var port = process.env.PORT || 3000;
var mongojs = require('mongojs');
var bodyParser = require('body-parser');
var db = mongojs('products', ['displays']);
var apiVersion = "v1";
So I can get all the displays with:
app.get('/'+apiVersion+'/displays', function(req, res){
db.displays.find(function(err,docs){
if(err){
res.send(err);
}
else{
return res.json(docs);
}
});
});
OR get specific displays with id parameter:
// GET ONE ENTRY
app.get('/'+apiVersion+'/displays/:id', function(req,res){
db.displays.findOne({_id:mongojs.ObjectID(req.params.id)},function(err,doc){
if(err){
res.send(err);
}
else{
return res.json(doc);
}
});
});
The issue is just passing custom parameters. Tried to use mongo-querystring which kind of worked but, was unable to filter by hdmi_version=#.# or resolution=####x####. Also the documentation examples weren't completely clear to me.
Any help would be immensely appreciated.