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

In order to use the User model, you need to include this file by adding the following require in the<br />

config/mongoose.js file (just before the return db; statement):<br />

1 require('../app/models/user.server.model');<br />

Create a user<br />

In order to keep things nice and tidy, you’ll create a Users controller which will handle all the requests<br />

for user related operations. In the app/controllers folder create a users.server.controller.js file and<br />

place the following code in it:<br />

1 var User = require('mongoose').model('User');<br />

2<br />

3 exports.create = function(req, res, next) {<br />

4 var user = new User(req.body);<br />

5 user.save(function(err) {<br />

6 if (err) {<br />

7 return next(err);<br />

8 }<br />

9 else {<br />

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

11 }<br />

12 });<br />

13 };<br />

In the app/routes folder create a file named users.server.routes.js and paste the following code:<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);<br />

5 };<br />

In the config/express.js file add the following route definition:<br />

1 require('../app/routes/users.server.routes.js')(app);<br />

This is all we need for the RESTful user saving API, and in order to test it run

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

Saved successfully!

Ooh no, something went wrong!