Monday, 18 May 2020

In case you're not using mongoose default connection

So I've recently started a side project to learn how to write backend in Node. I did some projects in React and had C#/.NET background in terms of backend, but I've never really done any server side programming in Node.So I decided to get my hands on this by creating some small REST API. I've put up Express, set up TypeScript, downloaded mongoose, made some endpoints with database queries - everything seemed fine. I created appropriate frontend and deployed application. But in one place in the app where there are two simultaneous API calls I was getting randomly some CORS errors in one of them. I looked up request headers and CORS config on the server and everything seemed fine.After a few hours of debugging and research on the internet I realized that like a complete moron I was instantiating a new mongoose connection and closing it on each request. This led to this strange bug I was encountering in my app.I probably skipped too much in terms of reading mongoose documentation and just started using it in a fashion that I would do so in C#/Java like initializing a connection with using statement or try/catch/finally to eventually close it at some point. Seems that this is not a case in Node and mongoose.Anyway, if anyone has read this post up to this point and is making such mistake, please stop. After removing all those unnecessary connections and adding a default one my app behaves 2x faster (not to mention getting rid of this frustrating bug).Stay safe and happy coding.

Submitted May 18, 2020 at 05:12PM by DazzlingArtichoke

No comments:

Post a Comment