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 62<br />

• findByIdAndRemove()¹²⁰<br />

Since you’re already using the userById() method, you’re going to use the findByIdAndRemove()<br />

method.<br />

In your app/controllers/users.server.controller.js file add a new delete() method:<br />

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

2 req.user.remove(function(err) {<br />

3 if (err) {<br />

4 return next(err);<br />

5 }<br />

6 else {<br />

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

8 }<br />

9 })<br />

10 };<br />

Now, in app/routes/users.server.routes.js file change the route with the userId parameter to be<br />

like this:<br />

1 app.route('/users/:userId').get(users.read).put(users.update).delete(users.delet\<br />

2 e);<br />

To test the delete method, run node server and issue a DELETE request, example with curl (OFC<br />

replace id] as before):<br />

1 $ curl -X DELETE localhost:1337/users/[id]<br />

Few additional goodies<br />

Indexes<br />

A unique index validates the uniqueness of a document field across a collection. Since you most<br />

likely want the username to be unique, you have to add this to your User model:<br />

¹²⁰http://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove

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

Saved successfully!

Ooh no, something went wrong!