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.

109 lines
2.0 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. .exec(function(err, ocinara) {
  68. if (err) return done(err);
  69. console.log('"%s" console _id: %s', ocinara.name, ocinara.consoles[0]);
  70. // population of existing document
  71. ocinara.populate('consoles', function(err) {
  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. }
  83. function done(err) {
  84. if (err) console.error(err);
  85. Console.remove(function() {
  86. Game.remove(function() {
  87. mongoose.disconnect();
  88. });
  89. });
  90. }