How to specify MongoDB key / value parameters in $ http.get with AngularJS controller?

I am using MEAN stack for a web application. In my .js controller, I have the following:

var refresh3 = function() {
    $http.get('/users').success(function(response) {
        console.log("I got the data I requested");
        $scope.users = response;
        $scope.contact3 = "";
    });
};

refresh3();

      

This drops every object in the "users" collection from my MongoDB. How can I add parameters to this to return, for example, only objects where "name" is "Bob"? I tried adding options to the parentheses / users using:

$http.get('/users', {params:{"name":"Bob"}})

      

I've tried variations of this too, but no luck. Any help would be appreciated!

+3


source to share


1 answer


If your server receives data

(and it should, since it is $http.get('/users', {params:{"name":"Bob"}})

correct)

On the server side, use a query string:

req.query

      

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 WAS THE NUMBER?



You indicated in your comments that your server is configured to respond to a app.get('/users')

GET request like this:

db.users.find(function (err, docs) {
 // docs is an array of all the documents in users collection
 console.log(docs); res.json(docs); }); });

      

So, I believe your angularjs $ http get is correct and your server is getting the parameters {"name":"Bob"}

as you would expect; he just doesn't know what to do with them: all he has to do is return the entire collection in the specific case of a app.get('/users')

GET request .


AS A SERVER CONFIGURATION FOR REST

You don't need to reinvent the wheel on the server.

Rather, you might consider using middleware to automate the task (in this case, the task is to issue a proper MongoDb query when you receive a get request with parameters from the client)

eg. express-restify-mongoose middleware

+2


source







All Articles