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.

112 lines
2.2 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. }, function (err, nintendo64, superNintendo) {
  46. if (err) return done(err);
  47. Game.create({
  48. name: 'Legend of Zelda: Ocarina of Time'
  49. , developer: 'Nintendo'
  50. , released: new Date('November 21, 1998')
  51. , consoles: [nintendo64]
  52. }, {
  53. name: 'Mario Kart'
  54. , developer: 'Nintendo'
  55. , released: 'September 1, 1992'
  56. , consoles: [superNintendo]
  57. }, function (err) {
  58. if (err) return done(err);
  59. example();
  60. })
  61. })
  62. }
  63. /**
  64. * Population
  65. */
  66. function example () {
  67. Game
  68. .find({})
  69. .exec(function (err, games) {
  70. if (err) return done(err);
  71. console.log('found %d games', games.length);
  72. var options = { path: 'consoles', select: 'name released -_id' };
  73. Game.populate(games, options, function (err, games) {
  74. if (err) return done(err);
  75. games.forEach(function (game) {
  76. console.log(
  77. '"%s" was released for the %s on %s'
  78. , game.name
  79. , game.consoles[0].name
  80. , game.released.toLocaleDateString());
  81. })
  82. done()
  83. })
  84. })
  85. }
  86. function done (err) {
  87. if (err) console.error(err);
  88. Console.remove(function () {
  89. Game.remove(function () {
  90. mongoose.disconnect();
  91. })
  92. })
  93. }