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.

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