Skip to content

Commit

Permalink
feat(document): add isDirectSelected() to minimize isSelected() changes
Browse files Browse the repository at this point in the history
Fix #5063
  • Loading branch information
vkarpov15 committed Mar 30, 2017
1 parent 2d6bf66 commit 04fb701
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -1237,6 +1237,65 @@ Document.prototype.isSelected = function isSelected(path) {
return true;
};

/**
* Checks if `path` was explicitly selected. If no projection, always returns
* true.
*
* ####Example
*
* Thing.findOne().select('nested.name').exec(function (err, doc) {
* doc.isDirectSelected('nested.name') // true
* doc.isDirectSelected('nested.otherName') // false
* doc.isDirectSelected('nested') // false
* })
*
* @param {String} path
* @return {Boolean}
* @api public
*/

Document.prototype.isDirectSelected = function isDirectSelected(path) {
if (this.$__.selected) {
if (path === '_id') {
return this.$__.selected._id !== 0;
}

var paths = Object.keys(this.$__.selected);
var i = paths.length;
var inclusive = null;
var cur;

if (i === 1 && paths[0] === '_id') {
// only _id was selected.
return this.$__.selected._id === 0;
}

while (i--) {
cur = paths[i];
if (cur === '_id') {
continue;
}
if (this.$__.selected[cur] && this.$__.selected[cur].$meta) {
continue;
}
inclusive = !!this.$__.selected[cur];
break;
}

if (inclusive === null) {
return true;
}

if (path in this.$__.selected) {
return inclusive;
}

return !inclusive;
}

return true;
};

/**
* Executes registered validation rules for this document.
*
Expand Down

0 comments on commit 04fb701

Please sign in to comment.