Inital Commit
[oweals/finalsclub.git] / node_modules / mongoose / examples / schema.js
1
2 /**
3  * Module dependencies.
4  */
5
6 var mongoose = require('mongoose')
7   , Schema = mongoose.Schema;
8
9 /**
10  * Schema definition
11  */
12
13 var BlogPost = new Schema({
14     title     : String
15   , slug      : String
16   , date      : Date
17   , comments  : [Comments]
18 });
19
20 // recursive embedded-document schema
21
22 var Comments = new Schema();
23
24 Comments.add({
25     title     : { type: String, index: true }
26   , date      : Date
27   , body      : String
28   , comments  : [Comments]
29 });
30
31 /**
32  * Accessing a specific schema type by key
33  */
34
35 BlogPost.path('date')
36   .default(function(){
37      return new Date()
38    })
39   .set(function(v){
40      return v == 'now' ? new Date() : v;
41    });
42
43 /**
44  * Pre hook.
45  */
46
47 BlogPost.pre('save', function(next, done){
48   emailAuthor(done); // some async function
49   next();
50 });
51
52 /**
53  * Plugins
54  */
55
56 function slugGenerator (options){
57   options = options || {};
58   var key = options.key || 'title';
59   
60   return function slugGenerator(schema){
61     schema.path(key).set(function(v){
62       this.slug = v.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/-+/g, '');
63       return v;
64     });
65   };
66 };
67
68 BlogPost.plugin(slugGenerator());
69
70 /**
71  * Define model.
72  */
73
74 mongoose.model('BlogPost', BlogPost);