mkorszun
mkorszun

Reputation: 4571

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?

Upvotes: 2

Views: 1523

Answers (1)

Orelsanpls
Orelsanpls

Reputation: 23565

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

@example

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

Upvotes: 1

Related Questions