diff --git a/lib/model.js b/lib/model.js index 6f0e334948c..ec395bf132d 100644 --- a/lib/model.js +++ b/lib/model.js @@ -92,11 +92,11 @@ Model.prototype._getPopulationKeys = function getPopulationKeys (query) { // loop until we find an array schema if (pathSchema && pathSchema.caster) { if (!paths[path]) { - paths[path] = query.options.populate[name]; + paths[path] = {}; paths[path].sub = {}; } - paths[path].sub[pieces.slice(i).join('.')] = 1; + paths[path].sub[pieces.slice(i).join('.')] = query.options.populate[name]; hasKeys || (hasKeys = true); break; } @@ -229,8 +229,9 @@ Model.prototype.init = function init (doc, query, fn) { key = pkeys[pi]; if (subobj[key]) (function (key) { + total++; - self._populate(schema.schema.path(key), subobj[key], poppath, done); + self._populate(schema.schema.path(key), subobj[key], poppath.sub[key], done); function done (err, doc) { if (err) return error(err); subobj[key] = doc; diff --git a/test/model.ref.test.js b/test/model.ref.test.js index df1822efcd3..c59cd4147d2 100644 --- a/test/model.ref.test.js +++ b/test/model.ref.test.js @@ -1106,6 +1106,72 @@ module.exports = { }); }, + 'populating multiple children of a sub-array at a time': function () { + var db = start() + , User = db.model('RefUser', users) + , BlogPost = db.model('RefBlogPost', posts) + , Inner = new Schema({ + user: { type: ObjectId, ref: 'RefUser' } + , post: { type: ObjectId, ref: 'RefBlogPost' } + }) + , I = db.model('PopMultiChildrenOfSubDocInner', Inner) + var M = db.model('PopMultiChildrenOfSubDoc', new Schema({ + kids: [Inner] + })) + + User.create({ + name : 'Fan 1' + , email : 'fan1@learnboost.com' + , gender : 'male' + }, { + name : 'Fan 2' + , email : 'fan2@learnboost.com' + , gender : 'female' + }, function (err, fan1, fan2) { + should.strictEqual(err, null); + + BlogPost.create({ + title : 'woot' + }, { + title : 'yay' + }, function (err, post1, post2) { + should.strictEqual(err, null); + M.create({ + kids: [ + { user: fan1, post: post1, y: 5 } + , { user: fan2, post: post2, y: 8 } + ] + , x: 4 + }, function (err, m1) { + should.strictEqual(err, null); + + M.where('_id').in([m1]) + .populate('kids.user', ["name"]) + .populate('kids.post', ["title"], { title: "woot" }) + .run(function (err, objs) { + db.close(); + should.strictEqual(err, null); + + should.exist(objs); + should.strictEqual(objs.length, 1); + var o = objs[0]; + should.exist(o.kids); + should.strictEqual(o.kids.length, 2); + var k1 = o.kids[0]; + var k2 = o.kids[1]; + should.exist(k1.user); + should.exist(k1.post); + should.exist(k2.user); + should.not.exist(k2.post); + should.strictEqual(k1.user.name, "Fan 1"); + should.strictEqual(k1.post.title, "woot"); + should.strictEqual(k2.user.name, "Fan 2"); + }); + }); + }); + }); + }, + 'passing sort options to the populate method': function () { var db = start() , P = db.model('RefBlogPost', posts)