Skip to content

Instantly share code, notes, and snippets.

@baruchvlz
Last active March 24, 2016 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baruchvlz/39dea1ef92c685ae056e to your computer and use it in GitHub Desktop.
Save baruchvlz/39dea1ef92c685ae056e to your computer and use it in GitHub Desktop.
Simple Helper function to trim properties from MongoDB responses.
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
}
/**
* 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
}
@baruchvlz
Copy link
Author

MongoDB response object trim.

ES6, Node, and lodash:
Also using _id and __v as default trims

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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment