Ahmad Elmoualem
Ahmad Elmoualem

Reputation: 325

Nodejs get user by id

Am using the MEAN stack for an app, i have users that i register and log in using satellizer everything work well.

But when i try to get user by it's id i get nothing, i can do request to get all users but not by id.

Note am using Ionicframework as a forntEnd framework. Here is the code of my back end end point:

app.get('/api/me', function(req, res) {
  User.findById(req.user, function(err, user) {
    console.log(req.user);
    console.log(user);
    res.send(user);
  });
})

my Front end code the controller:

.controller('ProfileCtrl', function($scope, $http, $stateParams, $ionicLoading, $timeout, $stateParams) {

    $ionicLoading.show({
        template: 'Loading...'
    });

    $http.get('http://localhost:3000/api/me')
        .success(function(data) {
            console.log("Recived data via HTTP", data);

            $timeout(function() {
                $ionicLoading.hide();
                $scope.user = data;
            }, 1000);
        })
        .error(function() {
            console.log("Error while getting the data");
            $ionicLoading.hide();
        });
})

Request Header:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ar;q=0.6,fi;q=0.4,it;q=0.2,en-GB;q=0.2,en-CA;q=0.2
Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1NTAxYjAxMmExMjRlZjIwMTc4M2ExMTQiLCJleHAiOjE0MjcxMzk0NDV9.x9QEdE4E-Vh1SklCheiZqsnJsg8jGzdJnPx2RXeZqS8
Connection:keep-alive
Host:localhost:3000
Origin:http://localhost:8100
Referer:http://localhost:8100/

Upvotes: 1

Views: 12872

Answers (1)

Reto
Reto

Reputation: 3141

you missed an important part in your server call, the "ensureAuthenticated":

app.get('/api/me', ensureAuthenticated, function(req, res) {
   User.findById(req.user, function(err, user) {
    res.send(user);
 });
});

the ensureAuthenticate of this satellite example implemenation is a very simple version, it only puts the content of the token.sub into req.user. This is good enough for your query. Typically in a real app one would use passport middleware instead, load the user in the middleware and put it into req.user.

when using the mean stack typically req.user is set to the full user object, i.e. an instance of mongoose document. You want to search by id, so give the query an id:

try

User.findById(req.user._id, function(err, user) {

instead.

But, considering that req.user is already exactly the object that you are querying for, the whole query might just not be needed at all.

If you want to look up a different user than the authenticated one, you need to pass the id you want to query in the URL path, typically something like:

GET /api/users/{id}

then you can get this id using

req.params.id

and pass it to the findById() call

Upvotes: 3

Related Questions