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.

103 lines
1.8 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. function(err, nintendo64) {
  47. if (err) return done(err);
  48. Game.create({
  49. name: 'Legend of Zelda: Ocarina of Time',
  50. developer: 'Nintendo',
  51. released: new Date('November 21, 1998'),
  52. consoles: [nintendo64]
  53. },
  54. function(err) {
  55. if (err) return done(err);
  56. example();
  57. });
  58. }
  59. );
  60. }
  61. /**
  62. * Population
  63. */
  64. function example() {
  65. Game
  66. .findOne({name: /^Legend of Zelda/})
  67. .populate('consoles')
  68. .exec(function(err, ocinara) {
  69. if (err) return done(err);
  70. console.log(
  71. '"%s" was released for the %s on %s',
  72. ocinara.name,
  73. ocinara.consoles[0].name,
  74. ocinara.released.toLocaleDateString()
  75. );
  76. done();
  77. });
  78. }
  79. function done(err) {
  80. if (err) console.error(err);
  81. Console.remove(function() {
  82. Game.remove(function() {
  83. mongoose.disconnect();
  84. });
  85. });
  86. }