Skip to content

Commit

Permalink
refactor _populate method
Browse files Browse the repository at this point in the history
  • Loading branch information
aheckmann committed Dec 1, 2011
1 parent bd84f94 commit dd64de0
Showing 1 changed file with 34 additions and 34 deletions.
68 changes: 34 additions & 34 deletions lib/model.js
Expand Up @@ -115,50 +115,50 @@ Model.prototype._getPopulationKeys = function getPopulationKeys (query) {
*
* @param {SchemaType} schema type for the oid
* @param {Object} object id or array of object ids
* @param {Array} fields to select
* @param {Object} object specifying query conditions, fields, and options
* @param {Function} callback
* @api private
*/

Model.prototype._populate = function populate (schema, oid, options, fn) {
options = options || {};
if (Array.isArray(oid)) {
if (oid.length) {
var total = oid.length
, model = this.model(schema.caster.options.ref)
, arr = []
Model.prototype._populate = function populate (schema, oid, query, fn) {
if (!Array.isArray(oid)) {
var conditions = query.conditions || {};
conditions._id = oid;

options.conditions || (options.conditions = {});
options.conditions._id || (options.conditions._id = { $in: oid });
return this
.model(schema.options.ref)
.findOne(conditions, query.fields, query.options, fn);
}

model.find(options.conditions, options.fields, options.options, function (err, docs) {
if (err) return fn(err);
if (!oid.length) {
return fn(null, oid);
}

if (options.options && options.options.sort) {
return fn(null, docs);
}
var model = this.model(schema.caster.options.ref)
, conditions = query && query.conditions || {};
conditions._id || (conditions._id = { $in: oid });

// put back in original id order (using a hash reduces complexity from n*n to 2n)
var docHash = {};
docs.forEach(function (doc) {
docHash[doc._id] = doc;
});
oid.forEach(function (id) {
if (id in docHash) arr.push(docHash[id]);
});
fn(null, arr);
});
} else {
fn(null, oid);
model.find(conditions, query.fields, query.options, function (err, docs) {
if (err) return fn(err);

// user specified sort order?
if (query.options && query.options.sort) {
return fn(null, docs);
}
} else {
options.conditions || (options.conditions = {});
options.conditions._id = oid;

this
.model(schema.options.ref)
.findOne(options.conditions, options.fields, options.options, fn)
}
// put back in original id order (using a hash reduces complexity from n*n to 2n)
var docHash = {};
docs.forEach(function (doc) {
docHash[doc._id] = doc;
});

var arr = [];
oid.forEach(function (id) {
if (id in docHash) arr.push(docHash[id]);
});

fn(null, arr);
});
};

/**
Expand Down

0 comments on commit dd64de0

Please sign in to comment.