2

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?

mkorszun
  • 4,461
  • 6
  • 28
  • 43

1 Answers1

1

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

Community
  • 1
  • 1
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
  • But it might get complicated with list of documents with nested ones, isn't it? – mkorszun Nov 10 '16 at 10:37
  • Yeah it can be tricky, but there is none other choice to remove null attributes from mongoose answer. I've edited my post with some code to help you in your task. – Orelsanpls Nov 10 '16 at 12:10
  • OK, this works for me. BTW, would it be possible to override toJSON for all my mongoose models? – mkorszun Nov 10 '16 at 15:18
  • A soluce can be to create your own `new Schema()` like new `CustomSchema()`, that's make the `new Schema()` and the `toJSON()` override. You can take a look at [mongoose plugins](http://mongoosejs.com/docs/plugins.html) if you have some time, idk if you can do it using it tho. – Orelsanpls Nov 10 '16 at 15:22