PageRenderTime 69ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/schema.js

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