18.05.2016 Views

Mittwoch, 18. Mai, 2016

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

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

2 User.findByIdAndUpdate(req.user.id, req.body, function(err, user) {<br />

3 if (err) {<br />

4 return next(err);<br />

5 }<br />

6 else {<br />

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

8 }<br />

9 });<br />

10 };<br />

Now update your app/routes/users.server.routes.js file to this (.put(users.update) is the novelty in<br />

this file):<br />

1 var users = require('../../app/controllers/users.server.controller');<br />

2<br />

3 module.exports = function(app) {<br />

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

5<br />

6 app.route('/users/:userId').get(users.read).put(users.update);<br />

7<br />

8 app.param('userId', users.userByID);<br />

9 };<br />

You can test this with a PUT command:<br />

1 $ curl -X PUT -H "Content-Type: application/json" -d '{"name": "UpdatedName"}' l\<br />

2 ocalhost:1337/users/[_id]<br />

where _id is, of course, the valid id of some user.<br />

Delete the user<br />

I hope that by now you’re seeing the pattern here - Mongoose model has several available methods<br />

to remove an existing document:<br />

• remove()¹¹⁸<br />

• findOneAndRemove()¹¹⁹<br />

¹¹⁸http://mongoosejs.com/docs/api.html#model_Model.remove<br />

¹¹⁹http://mongoosejs.com/docs/api.html#model_Model.findOneAndRemove

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

Saved successfully!

Ooh no, something went wrong!