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.

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