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.3 KiB

  1. var mongoose = require('../../lib');
  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: [{
  21. type: Schema.Types.ObjectId,
  22. ref: 'Console'
  23. }]
  24. });
  25. var Game = mongoose.model('Game', gameSchema);
  26. /**
  27. * Connect to the console database on localhost with
  28. * the default port (27017)
  29. */
  30. mongoose.connect('mongodb://localhost/console', function(err) {
  31. // if we failed to connect, abort
  32. if (err) throw err;
  33. // we connected ok
  34. createData();
  35. });
  36. /**
  37. * Data generation
  38. */
  39. function createData() {
  40. Console.create(
  41. {
  42. name: 'Nintendo 64',
  43. manufacturer: 'Nintendo',
  44. released: 'September 29, 1996'
  45. },
  46. {
  47. name: 'Super Nintendo',
  48. manufacturer: 'Nintendo',
  49. released: 'August 23, 1991'
  50. },
  51. function(err, nintendo64, superNintendo) {
  52. if (err) return done(err);
  53. Game.create(
  54. {
  55. name: 'Legend of Zelda: Ocarina of Time',
  56. developer: 'Nintendo',
  57. released: new Date('November 21, 1998'),
  58. consoles: [nintendo64]
  59. },
  60. {
  61. name: 'Mario Kart',
  62. developer: 'Nintendo',
  63. released: 'September 1, 1992',
  64. consoles: [superNintendo]
  65. },
  66. function(err) {
  67. if (err) return done(err);
  68. example();
  69. }
  70. );
  71. }
  72. );
  73. }
  74. /**
  75. * Population
  76. */
  77. function example() {
  78. Game
  79. .find({})
  80. .exec(function(err, games) {
  81. if (err) return done(err);
  82. console.log('found %d games', games.length);
  83. var options = {path: 'consoles', select: 'name released -_id'};
  84. Game.populate(games, options, 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[0].name,
  91. game.released.toLocaleDateString()
  92. );
  93. });
  94. done();
  95. });
  96. });
  97. }
  98. function done(err) {
  99. if (err) console.error(err);
  100. Console.remove(function() {
  101. Game.remove(function() {
  102. mongoose.disconnect();
  103. });
  104. });
  105. }