scottksmith95 / beerlocker

Source code for Beer Locker tutorials
http://scottksmith.com/blog/2014/05/02/building-restful-apis-with-node/
426 stars 263 forks source link

TypeError: Cannot read property '_id' of undefined #7

Open calvinKG opened 7 years ago

calvinKG commented 7 years ago

Hi,

Am getting this error after adding beer.userId = req.user._id , to the beer controller.

TypeError: Cannot read property '_id' of undefined

Code beer_controller.js `var Beer = require('../models/beer'); var User = require('../models/user');

// Create endpoint /api/beers for POST exports.postBeers = function(req, res) { // Create a new instance of the Beer model var beer = new Beer();

// Set the beer properties that came from the POST data
beer.name = req.body.name;
beer.type = req.body.type;
beer.quantity = req.body.quantity;
beer.userId = req.user._id; // where the error is 

// Save the beer and check for errors
beer.save(function(err) {
    if (err)
        return res.send(err);

    res.json({ message: 'Beer added to the locker!', data: beer });
});

};

// Create endpoint /api/beers for GET exports.getBeers = function(req, res) { // Use the Beer model to find all beer Beer.find({ userId: req.user._id }, function(err, beers) { if (err) return res.send(err);

    res.json(beers);
});

};

// Create endpoint /api/beers/:beer_id for GET exports.getBeer = function(req, res) { // Use the Beer model to find a specific beer Beer.find({ userId: req.user._id, _id: req.params.beer_id }, function(err, beer) { if (err) return res.send(err);

    res.json(beer);
});

};

// Create endpoint /api/beers/:beer_id for PUT exports.putBeer = function(req, res) { // Use the Beer model to find a specific beer Beer.update({ userId: req.user._id, _id: req.params.beer_id }, { quantity: req.body.quantity }, function(err, num, raw) { if (err) return res.send(err);

    res.json({ message: num + ' updated' });
});

};

// Create endpoint /api/beers/:beer_id for DELETE exports.deleteBeer = function(req, res) { // Use the Beer model to find a specific beer and remove it Beer.remove({ userId: req.user._id, _id: req.params.beer_id }, function(err) { if (err) return res.send(err);

    res.json({ message: 'Beer removed from the locker!' });
});

};`

TheFive commented 7 years ago

Hi Calvin,

the error indicates, that the authorization was not done correctly. Typically the req.user is set during the auth process. May be just the authorization when you try to post the data is missing ?

Christoph

LuizHAP commented 7 years ago

@TheFive i get the same error error1 error2

TheFive commented 7 years ago

wich beerlocker server are you working with 1,2,3...

LuizHAP commented 7 years ago

@TheFive 3.2

TheFive commented 7 years ago

you should add more information, when the error occurs (which version, which step in the blog you are evaluating). Just a hint, where you can search. In the auth file, the user is taken from the database: https://github.com/scottksmith95/beerlocker/tree/master/beerlocker-3.2/controllers The function User.findOne retrieves the users from the database. just add a console.log(user) in line 10, and you can see, what the result is.

(i assume, there is no user, so req.user is NULL at the stage, where the error occurs)

TheFive commented 7 years ago

Thats typically, how i learn, put as much console.log in the source as you need to understand, what is going on.

LuizHAP commented 7 years ago

@TheFive Ok. I put one user, and i can get them when i GET /api/users

[
  {
    "_id": "59166bf3d4de2b11707adbd8",
    "username": "luiz",
    "password": "$2a$05$JoE8wWw1uZ5eAC8w26PYzudMmRdj8.G3sAnU7fU5sHKsNe613GEta",
    "__v": 0
  }
]

When i can GET /api/beers, catch that error above. I don't understand how i can use that authentication.

calvinKG commented 7 years ago

@LuizHAP

Your missing the isAuthenticated function that need to be added for each call to our API

From the tutorial " The last piece is to update our server.js file to include the passport package, initialize it with our express app, and call the isAuthenticated function for each call to our API. Open up server.js and update it as follows."

image

calvinKG commented 7 years ago

Thanks @TheFive for the head-up

rohaanuv commented 4 years ago

I get this error at frontend. It causes due to, it is not executing state means isAuthenticated unlike this const { user, token } = isAuthenticated(); just add 'isAuthenticated()' in event like submit, It works !! For backend all private or protected routes must include isSignedIn, isAuthenticated, or specific user group auth, middleware must include