I want to use Mongoose's bulk operation for upserting transactions. For each of my transactions I want to process them in a loop and within that loop I need to use a promise. After that promise resolved, I want to add the upsert to the bulk.
My problem here is, that although I await
for every promise to finish, the bulk is executed at the end of the function before any of the promises is resolved. What am I doing wrong or how can I fix this?
const bulkTransactions = Transaction.collection.initializeUnorderedBulkOp();
transactions.forEach( async (transaction: any) => {
// do some suff, fill transaction_data
await Utils.processTransactionType(transaction).then((action: any) => {
if (action) {
// do other stuff
}
bulkTransactions.find({_id: hash}).upsert().replaceOne(transaction_data);
}).catch((err: Error) => {
// log error
});
});
await bulkTransactions.execute().catch((err: Error) => {
// log error
});