How to connect to db, then read collection into array, before using data in array

Posted January 15, 2019 1.2k views
Node.jsJavaScriptUbuntu 18.04

Promises and async/await somehow don’t work as I’m coding them. I must (1) connect to db, (2) read collections into arrays, then (3) use data in arrays, IN THAT ORDER. I have not figured out how to force MongoDB + Node.js + JavaScript to do that. It keeps trying to access collections before the db is really connected, and to use data in the arrays before they are really loaded from the collections.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
1 answer

No idea if anyone can help you here but IMO it’s all about the logic within your code, a few conditionals should help you achieve this.

If DB connection = True then
read the collection (select * from your table where date between etc.) > collection dict
If collection dict > 1 then
use the data in arrays[your stuff in here]
wait (add some logic flags in here)
throw error message (‘Can't connect’)

Don’t rely too much on my logic but this could be the big picture, there’s more needed to make it usable.