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