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

1 process.env.NODE_ENV = process.env.NODE_ENV || 'development';<br />

2<br />

3 var config = require('./config/config'),<br />

4 mongoose = require('./config/mongoose'),<br />

5 express = require('./config/express'),<br />

6<br />

7 var db = mongoose(),<br />

8 app = express();<br />

9<br />

10 app.listen(config.port);<br />

11<br />

12 module.exports = app;<br />

13 console.log(process.env.NODE_ENV + ' server running at http://localhost:' + con\<br />

14 fig.port);<br />

Mongoose configuration file has to be loaded before any other configuration in the server.js file<br />

(except the config module) because any module that is loaded after this module will be able to use<br />

its models without loading it by itself.<br />

If you execute node server command in your terminal and get an error like ‘Error: failed to connect<br />

to [localhost:27017]’, make sure your MongoDB instance (mongod) is running. Also, if you get another<br />

error like ‘ERROR: Insufficient free space for __journal files’, make sure that you have at least 3379MB<br />

available on the drive where you installed it.<br />

Mongoose schemas<br />

Since MongoDB doesn’t enforce the documents to have the same structure, Mongoose offers just<br />

that by using a Schema object to define a list of properties, each with its own type and constraints.<br />

To create a schema, create a new file named user.server.model.jsin the app/models folder and paste<br />

the following code:<br />

1 var mongoose = require('mongoose'),<br />

2 Schema = mongoose.Schema;<br />

3<br />

4 var UserSchema = new Schema({<br />

5 name: String,<br />

6 email: String,<br />

7 username: String,<br />

8 password: String,<br />

9 });<br />

10<br />

11 mongoose.model('User', UserSchema);

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

Saved successfully!

Ooh no, something went wrong!