Last active
August 29, 2015 14:24
-
-
Save ijmccallum/1b1612b84ce436bc5af4 to your computer and use it in GitHub Desktop.
Figuring out Mongoose's populate function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Document.prototype.populate = function populate () { | |
//if no args are passed, don't bother doing anything | |
if (0 === arguments.length) return this; | |
var pop = this.$__.populate || (this.$__.populate = {}); | |
var args = utils.args(arguments); | |
var fn; | |
if ('function' == typeof args[args.length-1]) { | |
fn = args.pop(); | |
} | |
// allow `doc.populate(callback)` | |
if (args.length) { | |
// use hash to remove duplicate paths | |
var res = utils.populate.apply(null, args); | |
for (var i = 0; i < res.length; ++i) { | |
pop[res[i].path] = res[i]; | |
} | |
} | |
if (fn) { | |
var paths = utils.object.vals(pop); | |
this.$__.populate = undefined; | |
this.constructor.populate(this, paths, fn); | |
} | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/Automattic/mongoose/blob/master/bin/mongoose.js#L2415