facebookinstagrammailtwitter

verwebbt

Response Builder for express and mongoose

This article is very nerdy and probably not interesting and/or understandable if you’re not a nerd-node-programmer. Instead watch this cute sleepy duckling.

tl;dr I made a small node module, it’s a simple file, take this gist, check it out, maybe it is useful.

Today I ran into a few problems with my mongoose models. Everything got messy and it felt like I was fixing something in one function and a causing a bug in another function. Before I go on I summarize my struggle shortly:

  • I have two models: an user model and an upload model.
  • The user model references to all uploads of an user. The upload model references to the user which uploaded the file.
  • I have a method in the upload model which needs to access data from the populated user model.
  • The model’s response isn’t the schema. I transform it before sending it.
  • I want a clean and unified response object model.
  • The controller shouldn’t end in a big mess.

Understood it? Me neither. What a fucking mess. I lost track of my files, functions were all over the place, and lastly I tried to populate the models which caused bugs everywhere. It felt like I need to sit in my shower, drink a really bad whisky and cry a lot. 

I said bye-bye to my plan to save database queries and decided to refactor my models and controllers (as I usually do every day). My new plan was to see in the controller how the response is structured and where the data is coming from. Everything else – like the queries and the building of the response – is in a separate module. Anyway this would repeat over and over in every controller function. Excluding it from the controller is nice and DRY.

The result:
I wrote a small node module. It takes an array describing which models should be loaded and how the response should look like. Also it can take some URL parameters to thin out the object based on them. The module returns a promise fulfilled with your desired response object.

rob2

I’m not quite sure if this is generally helpful, but I made it a gist. There’s a small readme and you can see how easy it is to create your response. Maybe someone can benefit from it.

This post is brought to you by: „I don’t want to add codeblocks to my WordPress Theme now, so I simply link to a gist somewhere at the end of the article.“

Comments