Last active
March 24, 2016 18:36
-
-
Save baruchvlz/39dea1ef92c685ae056e to your computer and use it in GitHub Desktop.
Simple Helper function to trim properties from MongoDB responses.
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
import _ from 'lodash' | |
/** | |
* Trim Response function | |
* Trim Object with given keys in Array | |
* @param obj || array of objects | |
* @param array | |
* @return obj | |
**/ | |
export function trimResponse( toTrim, array = []){ | |
// Default Trims | |
let trimArray = ['_id', '__v'] | |
if(array.length > 0) | |
trimArray = _.union(trimArray, array) | |
// Check if toTrim is an Array of Objects | |
if(Array.isArray(toTrim)){ | |
for(let i = 0; i < toTrim.length; i++){ | |
for(let j = 0; j < trimArray.length; j++){ | |
toTrim[i][trimArray[j]] = undefined | |
} | |
} | |
} | |
else{ | |
for(let i = 0; i < trimArray.length; i++){ | |
toTrim[trimArray[i]] = undefined | |
} | |
} | |
// Return trimmed object | |
return toTrim | |
} |
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
/** | |
* Trim Response function | |
* Trim MongoDB Object with given keys in Array | |
* @param obj || array of objects | |
* @param array | |
* @return obj | |
**/ | |
function trimResponse( toTrim, array ){ | |
// If no array passed, default to _id | |
if(!array) | |
array = ['_id'] | |
// Check if toTrim is an Array of Objects | |
if(Array.isArray(toTrim)){ | |
for(var i = 0; i < toTrim.length; i++){ | |
for(var j = 0; j < array.length; j++){ | |
toTrim[i][array[j]] = undefined | |
} | |
} | |
} | |
else{ | |
for(var k = 0; k < array.length; k++){ | |
toTrim[array[k]] = undefined | |
} | |
} | |
// Return trimmed object | |
return toTrim | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MongoDB response object trim.
ES6, Node, and lodash:
Also using
_id
and__v
as default trims