Zlatko
unread,Jan 24, 2019, 3:19:04 AM1/24/19Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to nodejs
Hello Sivi,
Your problem was likely not related to the unshift method at all. That method is synchronous, there is no race. Something else must have caused the issue: front-end bug, missing content type header, the database was down or your API server crashed, cross domain request, but not this. In that respect, there's no difference between the two methods.
On the other hand, I find the second approach better, because while functionally equivalent, it's easier to understand what's going on at a glance.
There are a few things you could do to improve it, though.
For one, that error handler at the end. You should really add a different status code. And for typical clients, you would also want to send this as JSON payload, not raw string - it would be easier to handle the error. Furthermore, this way you might be exposing unneeded details about your server to the clients, while at the same time, _,not_ providing useful info. E.g if I was building a client that used this API, I wouldn't know if the error is mine (e.g. Missing field or some validation), yours (e.g. Server had disk full and can't work any more), or database error (e.g. unique constraint on an index was violated).
Another point would be that you're making an unneeded call to the database (this is MongoDB, right?). You could do the whole transaction in one go, find and update with a single query (since you don't seem to be checking for e.g. Duplicated entries anyway).
The third thing would be that you could create a light service layer and take all these database shenanigans out of your endpoint route. The router would get the id parameter from the url and the title and content from the body, and pass it on to a service that hid all this stuff. It adds the overhead of an extra file, but brings in a much easier to maintain code, reusability etc.
Hope that helps.
Zlatko