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

January 15, 2019 462 views
Node.js JavaScript Ubuntu 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.

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]
else
wait (add some logic flags in here)
else
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.

Have another answer? Share your knowledge.