So middleware function exits before any logic executed.
Yes, but this is totally normal and 100% OK for node.js asynchronous code. That's how asynchronous code works. When the DB call completes, control flow resumes and you can either send a response or call next()
at that time. This is fine.
Is there any way to make asynchronous calls inside middleware?
Yes, and the way you are doing it is fine (minus some minor caveats listed below).
If not, is there any workaround?
No workaround necessary. This is how node.js works by design. All network I/O in node.js is asynchronous.
A few minor notes
- Make sure you either send a response OR call
next()
in every possible branch of your database callback function logic: error, someCondition is true, and someCondition is false. If any of your logic can end up in a branch that doesn't respond to the request and doesn't callnext()
the request will just hang until it fails due to a timeout. Your snippet above is missing error handling, which you need to do. - Move your mongoose connect call to application startup time. Don't connect on each request.
- Move your mongoose model definition out to a separate module
Config.js