thoughts/node_modules/mongoose/examples/population-basic.js
node_modules/mongoose/examples/population-basic.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 .populate('consoles')
75 .exec(function (err, ocinara) {
76 if (err) return done(err);
77
78 console.log(
79 '"%s" was released for the %s on %s'
80 , ocinara.name
81 , ocinara.consoles[0].name
82 , ocinara.released.toLocaleDateString());
83
84 done();
85 })
86}
87
88function done (err) {
89 if (err) console.error(err);
90 Console.remove(function () {
91 Game.remove(function () {
92 mongoose.disconnect();
93 })
94 })
95}