18.05.2016 Views

Mittwoch, 18. Mai, 2016

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

MongoDB CRUD the MVC way with Passport Authentication 59<br />

1 app.route('/users').post(users.create).get(users.list);<br />

In order to test this run node server and enter http://localhost:1337/users¹¹² in your browser.<br />

Find one user<br />

So, previous functionality gives you the list of all the users, but in order to show only one specific<br />

user in the app/controllers/users.server.controller.js file add the following code:<br />

1 exports.read = function(req, res) {<br />

2 res.json(req.user);<br />

3 };<br />

4<br />

5 exports.userByID = function(req, res, next, id) {<br />

6 User.findOne({<br />

7 _id: id<br />

8 },<br />

9 function(err, user) {<br />

10 if (err) {<br />

11 return next(err);<br />

12 }<br />

13 else {<br />

14 req.user = user;<br />

15 next();<br />

16 }<br />

17 }<br />

18 );<br />

19 };<br />

The read() method just responds with a JSON representation of the req.user object. The userById()<br />

method is populating the req.user object, which you will use as a middleware to deal with the<br />

manipulation of single documents when performing read, delete, and update operations.<br />

Now, modify your app/routes/users.server.routes.js file to look like this:<br />

¹¹²http://localhost:1337/users

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!