Currently i'm having huge problem when working with async function. The first thing i'm trying to compare my deleteArray (that has the current data that needs to be in the collection) with the data in the collection.
static async updateDocsInCollection(data) {
let deleteArray= [];
// Insert all data into array.
data.forEach(async (elem) => {
deleteArray.push(elem.serial);
}
MongoClient.connect('mongodb://' + config.database.host + ':' + config.database.port, { useNewUrlParser: true }, async function(err,db){
if (err) throw err;
// Get the current documents from "inventory" collection".
await dbo.collection("inventory").find({}).toArray(function(err, res) {
if (err) throw err;
// Iterate through res array and see if res element exists in
// deleteArray
res.forEach((elem) =>{
if(!deleteArray.includes(elem.serial)){
// if it don't, push it.
deleteArray.push(elem)
console.log(elem.serial + " Pushed into array");
}
});
});
// Iterate through deleteArray and delete it from collection.
deleteArray.forEach((elem) =>{
console.log(elem);
dbo.collection("onlineplayerservice").findOneAndDelete({ 'serial': elem.serial});
});
// closing db-connection.
db.close();
});
The problem is that the code does not run in the right order because I cannot iterate through deleteArray even though I see (according to console.log) that data is entered there.
Do you have any tips on how I can do to ensure that this function is synchronized?