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