javascript - How do I specify MongoDB key/value parameters in an $http.get with an AngularJS controller? -
i'm using mean stack web app. in controller.js, have following:
var refresh3 = function() { $http.get('/users').success(function(response) { console.log("i got data requested"); $scope.users = response; $scope.contact3 = ""; }); }; refresh3();
this pulls every object in "users" collection mongodb. how add parameters bring back, example, objects "name" : "bob" ? have tried adding parameters in '/users' parentheses using:
$http.get('/users', {params:{"name":"bob"}})
i've tried variants of that, no luck. appreciated!
if server receiving data
(and should, $http.get('/users', {params:{"name":"bob"}})
correct)
on server side, make use of query string:
req.query
like so:
app.get('/users', function(req,res){ if(req.query.name){ db.users.find({"name":req.query.name},function (err, docs) { console.log(docs); res.json(docs); }); } else{ db.users.find(function (err, docs) { console.log(docs); res.json(docs); }); } });
what issue?
you hinted in comments server set respond app.get('/users')
request so:
db.users.find(function (err, docs) { // docs array of documents in users collection console.log(docs); res.json(docs); }); });
so believe angularjs $http correct, , server receiving parameters {"name":"bob"}
should; doesn't know them: set return whole collection in particular case of app.get('/users')
request.
how configure server rest
you not have re-invent wheel on server.
rather, consider using middleware automate task (in present case, task issue proper mongodb request when receive query parameters client)
Comments
Post a Comment