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.

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