Wednesday 22 April 2020

Better validation for "undefined" Arrays in req (bodyparser)

Hey out there,I try to build up a api for my website and struggle at one point. My api get data, which is sometimes stored in arrays. Like this one:"classifications": [{"primary": true,"segment": {"id": "KZFzniwnSyZfZ7v7nJ",Now I try to post this and try to save it with bodyparser in a specific variable like that:router.post("/test", async (req, res) => {const post = new Concert({id: req.body.classifications[0].segment.id;In usual that works, but if there are Objects, which has no classification[....] my code brokes, because it can`t read property '0'.So I try to check if this variable can be set, bevore I pass it to my Schema Object.router.post("/test", async (req, res) => {try {var id = req.body.classifications[0].segment.id;  } catch (error) {console.log("id doesn\t exist exist");   }`const post = new Concert({id: id});... post that to the dbThat works fine, but if I pass more and more variables and try to set that all, my code looks like shit. Are there better solutions for that?Greetings

Submitted April 22, 2020 at 04:34PM by xxCeonxx

No comments:

Post a Comment