Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement/populate method - #137 #250

Merged
merged 3 commits into from
Jan 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions lib/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -425,26 +425,41 @@ Model.prototype.populate = function (options, resultObj, fillPath) {
if (!resultObj) {
resultObj = self;
}
if (!options.path || !options.model) {

var ModelPathName = '';

if (typeof options === 'string') {
ModelPathName = this.$__.table.schema.attributes[options].options.ref;
} else if (options.path) {
ModelPathName = this.$__.table.schema.attributes[options.path].options.ref;
} else if (!options.path && !options.model) {
throw new Error('Invalid parameters provided to the populate method');
}
}

var Model = _filter(this.$__.table.base.models, function(model){
return model.$__.name === model.$__.options.prefix + options.model || model.$__.name === options.model;
return (
model.$__.name === model.$__.options.prefix + options.model ||
model.$__.name === options.model ||
model.$__.name === model.$__.options.prefix + ModelPathName ||
model.$__.name === ModelPathName
);
}).pop();

if (!Model) {
throw new Error('The provided model doesn\'t exists');
}

return Model
.get(self[options.path])
.get(self[options.path || options])
.then(function(target){
if (!target) {
throw new Error('Invalid reference');
}
self[options.path] = target;
fillPath = fillPath.concat(options.path);
self[options.path || options] = target;
fillPath = fillPath.concat(options.path || options);
deepSet(resultObj, fillPath, target);
if (options.populate) {
return self[options.path].populate(options.populate, resultObj, fillPath);
return self[options.path || options].populate(options.populate, resultObj, fillPath);
} else {
return resultObj;
}
Expand Down
Loading