schema.js 1.9 KB

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