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.

77 lines
1.2 KiB

  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. }