Skip to content

Instantly share code, notes, and snippets.

@ijmccallum
Last active August 29, 2015 14:24
Show Gist options
  • Save ijmccallum/1b1612b84ce436bc5af4 to your computer and use it in GitHub Desktop.
Save ijmccallum/1b1612b84ce436bc5af4 to your computer and use it in GitHub Desktop.
Figuring out Mongoose's populate function
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