thoughts/node_modules/mongoose/examples/population-across-three-collections.js
node_modules/mongoose/examples/population-across-three-collections.jsRaw
1
2var assert = require('assert')
3var mongoose = require('../');
4var Schema = mongoose.Schema;
5var ObjectId = mongoose.Types.ObjectId;
6
7/**
8 * Connect to the db
9 */
10
11var dbname = 'testing_populateAdInfinitum_' + require('../lib/utils').random()
12mongoose.connect('localhost', dbname);
13mongoose.connection.on('error', function() {
14 console.error('connection error', arguments);
15});
16
17/**
18 * Schemas
19 */
20
21var user = new Schema({
22 name: String,
23 friends: [{
24 type: Schema.ObjectId,
25 ref: 'User'
26 }]
27});
28var User = mongoose.model('User', user);
29
30var blogpost = Schema({
31 title: String,
32 tags: [String],
33 author: {
34 type: Schema.ObjectId,
35 ref: 'User'
36 }
37})
38var BlogPost = mongoose.model('BlogPost', blogpost);
39
40/**
41 * example
42 */
43
44mongoose.connection.on('open', function() {
45
46 /**
47 * Generate data
48 */
49
50 var userIds = [new ObjectId, new ObjectId, new ObjectId, new ObjectId];
51 var users = [];
52
53 users.push({
54 _id: userIds[0],
55 name: 'mary',
56 friends: [userIds[1], userIds[2], userIds[3]]
57 });
58 users.push({
59 _id: userIds[1],
60 name: 'bob',
61 friends: [userIds[0], userIds[2], userIds[3]]
62 });
63 users.push({
64 _id: userIds[2],
65 name: 'joe',
66 friends: [userIds[0], userIds[1], userIds[3]]
67 });
68 users.push({
69 _id: userIds[3],
70 name: 'sally',
71 friends: [userIds[0], userIds[1], userIds[2]]
72 });
73
74 User.create(users, function(err, docs) {
75 assert.ifError(err);
76
77 var blogposts = [];
78 blogposts.push({
79 title: 'blog 1',
80 tags: ['fun', 'cool'],
81 author: userIds[3]
82 })
83 blogposts.push({
84 title: 'blog 2',
85 tags: ['cool'],
86 author: userIds[1]
87 })
88 blogposts.push({
89 title: 'blog 3',
90 tags: ['fun', 'odd'],
91 author: userIds[2]
92 })
93
94 BlogPost.create(blogposts, function(err, docs) {
95 assert.ifError(err);
96
97 /**
98 * Population
99 */
100
101 BlogPost
102 .find({ tags: 'fun' })
103 .lean()
104 .populate('author')
105 .exec(function(err, docs) {
106 assert.ifError(err);
107
108 /**
109 * Populate the populated documents
110 */
111
112 var opts = {
113 path: 'author.friends',
114 select: 'name',
115 options: { limit: 2 }
116 }
117
118 BlogPost.populate(docs, opts, function(err, docs) {
119 assert.ifError(err);
120 console.log('populated');
121 var s = require('util').inspect(docs, { depth: null })
122 console.log(s);
123 done();
124 })
125 })
126 })
127 })
128});
129
130function done(err) {
131 if (err) console.error(err.stack);
132 mongoose.connection.db.dropDatabase(function() {
133 mongoose.connection.close();
134 });
135}