population-plain-objects.js 1.9 KB

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