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.

124 lines
2.4 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. }, {
  42. name: 'Super Nintendo'
  43. , manufacturer: 'Nintendo'
  44. , released: 'August 23, 1991'
  45. }, {
  46. name: 'XBOX 360'
  47. , manufacturer: 'Microsoft'
  48. , released: 'November 22, 2005'
  49. }, function (err, nintendo64, superNintendo, xbox360) {
  50. if (err) return done(err);
  51. Game.create({
  52. name: 'Legend of Zelda: Ocarina of Time'
  53. , developer: 'Nintendo'
  54. , released: new Date('November 21, 1998')
  55. , consoles: [nintendo64]
  56. }, {
  57. name: 'Mario Kart'
  58. , developer: 'Nintendo'
  59. , released: 'September 1, 1992'
  60. , consoles: [superNintendo]
  61. }, {
  62. name: 'Perfect Dark Zero'
  63. , developer: 'Rare'
  64. , released: 'November 17, 2005'
  65. , consoles: [xbox360]
  66. }, function (err) {
  67. if (err) return done(err);
  68. example();
  69. })
  70. })
  71. }
  72. /**
  73. * Population
  74. */
  75. function example () {
  76. Game
  77. .find({})
  78. .populate({
  79. path: 'consoles'
  80. , match: { manufacturer: 'Nintendo' }
  81. , select: 'name'
  82. , options: { comment: 'population' }
  83. })
  84. .exec(function (err, games) {
  85. if (err) return done(err);
  86. games.forEach(function (game) {
  87. console.log(
  88. '"%s" was released for the %s on %s'
  89. , game.name
  90. , game.consoles.length ? game.consoles[0].name : '??'
  91. , game.released.toLocaleDateString());
  92. })
  93. return done();
  94. })
  95. }
  96. /**
  97. * Clean up
  98. */
  99. function done (err) {
  100. if (err) console.error(err);
  101. Console.remove(function () {
  102. Game.remove(function () {
  103. mongoose.disconnect();
  104. })
  105. })
  106. }