population-of-existing-doc.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. }