node.js - Exclude null attributes from Mongoose query result -


i querying data using mongoose , returning response via express api. prevent null attributes being present in api response. there nice way via mongoose? recommended way of doing using express & mongoose?

you can override tojson mongoose schema methods remove attributes 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 have code that's gonna remove every null data on attributes 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


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -