arnaucube
arnaucube/thoughtsPublic Self-hosted repository
thoughts/node_modules/mongoose/examples/population/population-basic.js
node_modules/mongoose/examples/population/population-basic.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  .populate('consoles')
 82  .exec(function(err, ocinara) {
 83    if (err) return done(err);
 84
 85    console.log(
 86      '"%s" was released for the %s on %s',
 87      ocinara.name,
 88      ocinara.consoles[0].name,
 89      ocinara.released.toLocaleDateString()
 90    );
 91
 92    done();
 93  });
 94}
 95
 96function done(err) {
 97  if (err) console.error(err);
 98  Console.remove(function() {
 99    Game.remove(function() {
100      mongoose.disconnect();
101    });
102  });
103}