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

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

2 ...<br />

3 username: {<br />

4 type: String,<br />

5 unique: true<br />

6 },<br />

7 ...<br />

8 });<br />

Mongoose also supports secondary indexes using the index property. So, if you know that your<br />

application will use a lot of queries with the email field, you could optimize these queries by creating<br />

an email secondary index:<br />

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

2 ...<br />

3 email: {<br />

4 type: String,<br />

5 index: true<br />

6 },<br />

7 ...<br />

8 });<br />

Mongoose middleware<br />

Mongoose has pre and post middlewares which execute, as you may imagine, pre and post some<br />

operation. Template looks like this:<br />

1 UserSchema.pre('save', function(next) {<br />

2 if (something) {<br />

3 next()<br />

4 } else {<br />

5 next(new Error('No can do, sir!'));<br />

6 }<br />

7 });<br />

So, basically, before you save something to MongoDB some action is performed before that - you<br />

will use this later for hashing the password before saving it to the MongoDB.<br />

Mongoose lets you configure a lot more options like default values¹²¹, custom getters/setters¹²²,<br />

virtual attributes¹²³, custom methods and statics¹²⁴, custom validation¹²⁵, custom references to other<br />

¹²¹http://mongoosejs.com/docs/2.7.x/docs/defaults.html<br />

¹²²http://mongoosejs.com/docs/2.7.x/docs/getters-setters.html<br />

¹²³http://mongoosejs.com/docs/2.7.x/docs/virtuals.html<br />

¹²⁴http://mongoosejs.com/docs/2.7.x/docs/methods-statics.html<br />

¹²⁵http://mongoosejs.com/docs/2.7.x/docs/validation.html

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

Saved successfully!

Ooh no, something went wrong!