Jake Sellers
Jake Sellers

Reputation: 2439

Checking for object and property existance

I work with mongodb on a regular basis and before accessing a specific property from a query result, I write an existence check that often looks like this:

if(result && result.subObject1 && result.subObject1.property) { ... }

This is safest way to check the result stream, or any other object that I'm receiving, that I know of.

This works just fine, its just that most of the time I think to myself, "There's probably a better way to do this", there is.

I looked at a few related posts but none of them really addresses this, especially when dealing with (possibly) deeply nested objects.

Upvotes: 1

Views: 72

Answers (1)

s.d
s.d

Reputation: 29436

Avoid truth/false checks on data values themselves.

E.g.

request body : data : { temperature : -128, level : 42 } etc.

server validation : data must be sent and have temperature value set

validation code : if(data && data.temperature){//ok}else{//invalid input}

The above validation code will reject 0 and negative temperature values as well, while server's actual validation motive was to ensure temperature value is always set.

Hence checks should be clearly and separately defined:

function exists(val){ return val !== undefined && val !== null; }

function isNumber(val){ return !isNan(val); }

and combinations of these checks should be used.

For more robust checks, use modules like validator.

As far as deep checks are concerned, you will need to define a full and proper JSON schema first and then run a schema validator on it.

Upvotes: 1

Related Questions