I'm learning node and I have a piece of code that queries data in the db that i'd like to pass into a callback function. But I'd like to only return unique members.
This means that I have to go through the result of the query, and push the unique members into an array, then pass the array into the cb function.
The problem is, the input is also an array that i build the query off. So there's already a loop there.
I've taken a look at some previous SO threads with promises, await, etc. But I'm having some trouble implementing them with loops like in here.
static getDestination(envName, cb){
var ans = new Array();
var promises;
DataBase.initDB((db) => {
for (var i = 0; i < envName.length; i++){
db.collection('Environment').find({'environmentName' : envName[i]}, (err, data) => {
if (err) {
console.log('error getting data in getDestination()');
return;
}
data.toArray((err, content) => {
if (err) {
console.log('error converting cursor into array');
return;
}
else {
for (const doc of content){
if (!ans.includes(doc.destination)){
ans.push(doc.destination);
}
//cb(ans);
}
}
});
});
}
})
cb(ans);
}
Right now, the callback is just a console.log(ans), and it's printing out an empty array [].
If I call the callback in the innermost loop, it returns the proper members, but it gets called as the loop goes like:
[]
[ 'DEV' ]
[ 'DEV' ]
[ 'DEV', 'QA' ]
I'd like to get only the last line of the output. A thorough explanation would be amazing too!
EDIT: To my understanding, I should be creating an array of promises, and at every iteration of the loop, I should be creating a new promise with the operation as a parameter. Then at the end of everything, I can call
Promise.all(promises).then(cb(ans));
But I'm having trouble understanding which transaction should I create the promises on. Since if I create the promise in the innermost loop, the cb outside of the loop gets called before the first was even created.
EDIT:
exports.initDB = (cb) => {
console.log('Connecting...');
const uri = <mongo connection uri here>;
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
if (err) {
console.log('eror connecting to db');
console.log(err);
return;
}
cb(client.db(process.env.DB_NAME));
});
}