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.

95 lines
1.8 KiB

  1. var mongoose = require('mongoose')
  2. var Schema = mongoose.Schema;
  3. console.log('Running mongoose version %s', mongoose.version);
  4. /**
  5. * Console schema
  6. */
  7. var consoleSchema = Schema({
  8. name: String
  9. , manufacturer: String
  10. , released: Date
  11. })
  12. var Console = mongoose.model('Console', consoleSchema);
  13. /**
  14. * Game schema
  15. */
  16. var gameSchema = Schema({
  17. name: String
  18. , developer: String
  19. , released: Date
  20. , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }]
  21. })
  22. var Game = mongoose.model('Game', gameSchema);
  23. /**
  24. * Connect to the console database on localhost with
  25. * the default port (27017)
  26. */
  27. mongoose.connect('mongodb://localhost/console', function (err) {
  28. // if we failed to connect, abort
  29. if (err) throw err;
  30. // we connected ok
  31. createData();
  32. })
  33. /**
  34. * Data generation
  35. */
  36. function createData () {
  37. Console.create({
  38. name: 'Nintendo 64'
  39. , manufacturer: 'Nintendo'
  40. , released: 'September 29, 1996'
  41. }, function (err, nintendo64) {
  42. if (err) return done(err);
  43. Game.create({
  44. name: 'Legend of Zelda: Ocarina of Time'
  45. , developer: 'Nintendo'
  46. , released: new Date('November 21, 1998')
  47. , consoles: [nintendo64]
  48. }, function (err) {
  49. if (err) return done(err);
  50. example();
  51. })
  52. })
  53. }
  54. /**
  55. * Population
  56. */
  57. function example () {
  58. Game
  59. .findOne({ name: /^Legend of Zelda/ })
  60. .populate('consoles')
  61. .exec(function (err, ocinara) {
  62. if (err) return done(err);
  63. console.log(
  64. '"%s" was released for the %s on %s'
  65. , ocinara.name
  66. , ocinara.consoles[0].name
  67. , ocinara.released.toLocaleDateString());
  68. done();
  69. })
  70. }
  71. function done (err) {
  72. if (err) console.error(err);
  73. Console.remove(function () {
  74. Game.remove(function () {
  75. mongoose.disconnect();
  76. })
  77. })
  78. }