thoughts/node_modules/mongoose/examples/population/population-across-three-collections.js
node_modules/mongoose/examples/population/population-across-three-collections.jsRaw
1
2var assert = require('assert');
3var mongoose = require('../../lib');
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 * Generate data
47 */
48
49 var userIds = [new ObjectId, new ObjectId, new ObjectId, new ObjectId];
50 var users = [];
51
52 users.push({
53 _id: userIds[0],
54 name: 'mary',
55 friends: [userIds[1], userIds[2], userIds[3]]
56 });
57 users.push({
58 _id: userIds[1],
59 name: 'bob',
60 friends: [userIds[0], userIds[2], userIds[3]]
61 });
62 users.push({
63 _id: userIds[2],
64 name: 'joe',
65 friends: [userIds[0], userIds[1], userIds[3]]
66 });
67 users.push({
68 _id: userIds[3],
69 name: 'sally',
70 friends: [userIds[0], userIds[1], userIds[2]]
71 });
72
73 User.create(users, function(err) {
74 assert.ifError(err);
75
76 var blogposts = [];
77 blogposts.push({
78 title: 'blog 1',
79 tags: ['fun', 'cool'],
80 author: userIds[3]
81 });
82 blogposts.push({
83 title: 'blog 2',
84 tags: ['cool'],
85 author: userIds[1]
86 });
87 blogposts.push({
88 title: 'blog 3',
89 tags: ['fun', 'odd'],
90 author: userIds[2]
91 });
92
93 BlogPost.create(blogposts, function(err) {
94 assert.ifError(err);
95
96 /**
97 * Population
98 */
99
100 BlogPost
101 .find({tags: 'fun'})
102 .lean()
103 .populate('author')
104 .exec(function(err, docs) {
105 assert.ifError(err);
106
107 /**
108 * Populate the populated documents
109 */
110
111 var opts = {
112 path: 'author.friends',
113 select: 'name',
114 options: {limit: 2}
115 };
116
117 BlogPost.populate(docs, opts, function(err, docs) {
118 assert.ifError(err);
119 console.log('populated');
120 var s = require('util').inspect(docs, {depth: null, colors: true});
121 console.log(s);
122 done();
123 });
124 });
125 });
126 });
127});
128
129function done(err) {
130 if (err) console.error(err.stack);
131 mongoose.connection.db.dropDatabase(function() {
132 mongoose.connection.close();
133 });
134}