You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

119 lines
1.9 KiB

  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);