thoughts/node_modules/mongoose/examples/schema.js
node_modules/mongoose/examples/schema.jsRaw
1
2/**
3 * Module dependencies.
4 */
5
6var mongoose = require('mongoose')
7 , Schema = mongoose.Schema;
8
9/**
10 * Schema definition
11 */
12
13// recursive embedded-document schema
14
15var Comment = new Schema();
16
17Comment.add({
18 title : { type: String, index: true }
19 , date : Date
20 , body : String
21 , comments : [Comment]
22});
23
24var BlogPost = new Schema({
25 title : { type: String, index: true }
26 , slug : { type: String, lowercase: true, trim: true }
27 , date : Date
28 , buf : Buffer
29 , comments : [Comment]
30 , creator : Schema.ObjectId
31});
32
33var Person = new Schema({
34 name: {
35 first: String
36 , last : String
37 }
38 , email: { type: String, required: true, index: { unique: true, sparse: true } }
39 , alive: Boolean
40});
41
42/**
43 * Accessing a specific schema type by key
44 */
45
46BlogPost.path('date')
47.default(function(){
48 return new Date()
49 })
50.set(function(v){
51 return v == 'now' ? new Date() : v;
52 });
53
54/**
55 * Pre hook.
56 */
57
58BlogPost.pre('save', function(next, done){
59 emailAuthor(done); // some async function
60 next();
61});
62
63/**
64 * Methods
65 */
66
67BlogPost.methods.findCreator = function (callback) {
68 return this.db.model('Person').findById(this.creator, callback);
69}
70
71BlogPost.statics.findByTitle = function (title, callback) {
72 return this.find({ title: title }, callback);
73}
74
75BlogPost.methods.expressiveQuery = function (creator, date, callback) {
76 return this.find('creator', creator).where('date').gte(date).run(callback);
77}
78
79/**
80 * Plugins
81 */
82
83function slugGenerator (options){
84 options = options || {};
85 var key = options.key || 'title';
86
87 return function slugGenerator(schema){
88 schema.path(key).set(function(v){
89 this.slug = v.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/-+/g, '');
90 return v;
91 });
92 };
93};
94
95BlogPost.plugin(slugGenerator());
96
97/**
98 * Define model.
99 */
100
101mongoose.model('BlogPost', BlogPost);
102mongoose.model('Person', Person);