arnaucube
arnaucube/thoughtsPublic Self-hosted repository
thoughts/node_modules/mongoose/examples/population/population-of-existing-doc.js
node_modules/mongoose/examples/population/population-of-existing-doc.jsRaw
  1
  2var mongoose = require('../../lib');
  3var Schema = mongoose.Schema;
  4
  5console.log('Running mongoose version %s', mongoose.version);
  6
  7/**
  8 * Console schema
  9 */
 10
 11var consoleSchema = Schema({
 12  name: String,
 13  manufacturer: String,
 14  released: Date
 15});
 16var Console = mongoose.model('Console', consoleSchema);
 17
 18/**
 19 * Game schema
 20 */
 21
 22var gameSchema = Schema({
 23  name: String,
 24  developer: String,
 25  released: Date,
 26  consoles: [{
 27    type: Schema.Types.ObjectId,
 28    ref: 'Console'
 29  }]
 30});
 31var Game = mongoose.model('Game', gameSchema);
 32
 33/**
 34 * Connect to the console database on localhost with
 35 * the default port (27017)
 36 */
 37
 38mongoose.connect('mongodb://localhost/console', function(err) {
 39  // if we failed to connect, abort
 40  if (err) throw err;
 41
 42  // we connected ok
 43  createData();
 44});
 45
 46/**
 47 * Data generation
 48 */
 49
 50function createData() {
 51  Console.create(
 52    {
 53      name: 'Nintendo 64',
 54      manufacturer: 'Nintendo',
 55      released: 'September 29, 1996'
 56    },
 57    function(err, nintendo64) {
 58      if (err) return done(err);
 59
 60      Game.create({
 61        name: 'Legend of Zelda: Ocarina of Time',
 62        developer: 'Nintendo',
 63        released: new Date('November 21, 1998'),
 64        consoles: [nintendo64]
 65      },
 66      function(err) {
 67        if (err) return done(err);
 68        example();
 69      });
 70    }
 71  );
 72}
 73
 74/**
 75 * Population
 76 */
 77
 78function example() {
 79  Game
 80  .findOne({name: /^Legend of Zelda/})
 81  .exec(function(err, ocinara) {
 82    if (err) return done(err);
 83
 84    console.log('"%s" console _id: %s', ocinara.name, ocinara.consoles[0]);
 85
 86    // population of existing document
 87    ocinara.populate('consoles', function(err) {
 88      if (err) return done(err);
 89
 90      console.log(
 91        '"%s" was released for the %s on %s',
 92        ocinara.name,
 93        ocinara.consoles[0].name,
 94        ocinara.released.toLocaleDateString()
 95      );
 96
 97      done();
 98    });
 99  });
100}
101
102function done(err) {
103  if (err) console.error(err);
104  Console.remove(function() {
105    Game.remove(function() {
106      mongoose.disconnect();
107    });
108  });
109}