doc-methods.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. var mongoose = require('mongoose');
  2. var Schema = mongoose.Schema;
  3. console.log('Running mongoose version %s', mongoose.version);
  4. /**
  5. * Schema
  6. */
  7. var CharacterSchema = Schema({
  8. name: {
  9. type: String,
  10. required: true
  11. },
  12. health: {
  13. type: Number,
  14. min: 0,
  15. max: 100
  16. }
  17. });
  18. /**
  19. * Methods
  20. */
  21. CharacterSchema.methods.attack = function() {
  22. console.log('%s is attacking', this.name);
  23. };
  24. /**
  25. * Character model
  26. */
  27. var Character = mongoose.model('Character', CharacterSchema);
  28. /**
  29. * Connect to the database on localhost with
  30. * the default port (27017)
  31. */
  32. var dbname = 'mongoose-example-doc-methods-' + ((Math.random() * 10000) | 0);
  33. var uri = 'mongodb://localhost/' + dbname;
  34. console.log('connecting to %s', uri);
  35. mongoose.connect(uri, function(err) {
  36. // if we failed to connect, abort
  37. if (err) throw err;
  38. // we connected ok
  39. example();
  40. });
  41. /**
  42. * Use case
  43. */
  44. function example() {
  45. Character.create({name: 'Link', health: 100}, function(err, link) {
  46. if (err) return done(err);
  47. console.log('found', link);
  48. link.attack(); // 'Link is attacking'
  49. done();
  50. });
  51. }
  52. /**
  53. * Clean up
  54. */
  55. function done(err) {
  56. if (err) console.error(err);
  57. mongoose.connection.db.dropDatabase(function() {
  58. mongoose.disconnect();
  59. });
  60. }