mkorszun mkorszun - 1 year ago 143
Node.js Question

Exclude null attributes from Mongoose query result

I am querying my data using Mongoose and then returning it as a response via my express API. I would like to prevent null attributes being present in the API response. Is there a nice way to do it via Mongoose? What is the recommended way of doing this using express & Mongoose?

Answer Source

You can override the toJSON mongoose schema methods to remove the attributes from the returned json.


YourSchemaName.methods.toJSON = function() {
  var obj = this.toObject();

  if (obj.SOME_FIELD_NAME === null) delete obj.SOME_FIELD_NAME;
  return obj;

Nested Objects Handling

Here you have the code that's gonna remove every null data on attributes you have.

const removeEmpty = (obj) => {
  Object.keys(obj).forEach(key =>
    (obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key]) ||
    (obj[key] === '' || obj[key] === null) && delete obj[key]
  return obj;

source: how-do-i-remove-all-null-and-empty-string-values-from-a-json-object

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download