user4080876
user4080876

Reputation:

How to query mongoose for a user with his username

I have this route in my nodejs API app:

router.post('/user', function(req, res, next){
  if(!req.body.username){
    return res.status(400).json({message: 'Geen username'});
  }

  var user = {};

  User.find({ 'username': req.body.username}, function(err, foundUser){
    if(err)
      return next(err);

    if (foundUser) // check the value returned for undefined
    {
      user = foundUser;
    }
  });

  res.json(user);
});

However this just returns {} and I'm sure the username is in the database.

This is how I call the route in my angular app:

$scope.user = function() {
        $http({
            method: 'POST',
            url: "http://groep6api.herokuapp.com/user",
            headers: {
             'Content-Type': 'application/x-www-form-urlencoded'
             //'authentication': 'bearer' + $window.localStorage.getItem('token')
             },
            data: {username: $window.localStorage.getItem('username')},
            transformRequest: function(obj) {
                var str = [];
                for(var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            }
        }).success(function (result) {
            console.log(result);
        }).error(function(){

        });
    };

I'm fairly new to Angular and Nodejs and I tried User.find and User.findOne, but neither worked. How can I search mongoose for objects based on parameters?

Upvotes: 2

Views: 280

Answers (2)

Manu Masson
Manu Masson

Reputation: 1737

You need to put the res.json(); inside your findOne()

router.post('/user', function(req, res, next){ if(!req.body.username){ return res.status(400).json({message: 'Geen username'}); } var user = {}; User.findOne({ 'username': req.body.username}, function(err, foundUser){ if(err) return next(err); console.log(foundUser); 
// if this works everything's fine 
    if (foundUser) // check the value returned for undefined 
{ user = foundUser;  res.json(user); } }); 
     });

Upvotes: 0

Bagofjuice
Bagofjuice

Reputation: 382

You are returning the json before the mongoose call completes and so the user variable is empty. Try this:

router.post('/user', function(req, res, next){
    if(!req.body.username){
      return res.status(400).json({message: 'Geen username'});
    }

    var user = {};

    User.find({ 'username': req.body.username}, function(err, foundUser){
    if(err)
        return next(err);

    if (foundUser) // check the value returned for undefined
    {
      user = foundUser;
    }

    res.json(user);
  });

});

Upvotes: 2

Related Questions