Search code examples
node.jsmongoosees6-promise

Call a function on each object in an array in Node


I'm trying to batch together a database update to re-populate a mongo collection. I've created an object to hold the properties needed to lookup the data from an external source, and then add it back to a MongoDb collection.

The array looks like this:

const pops = [ 
    { table: 'SFAccounts',
      label: 'Account__c', 
      createListName: 'Accounts'
    },
    { table: 'SFTimes',
      label: 'CusTime__c', 
      createListName: 'Time'
    }]

I want to then create a function that takes 'table', 'label, and 'createListName' and it does something basically like this..

async function processData(table, label, createListName) {
    // Get some info from Salesforce 
    const dataFromSF = await getMetaDataFromSalesForce(table)
    // Extract the parts I actually need
    const relevantBits = dataFromSF.filter(field => field.name === label)
    //Create a new list in the db
    const createResult = await List.create( { name: createListName, values: relevantBits } )
    return createResult
}

The end goal is to get to something like

await Promise.all(processData(pops))

Which will await all the tables being pulled and populated into the database.


Solution

  • If you change the args of processData:

    async function processData({table, label, createListName}) {
        // Get some info from Salesforce 
        const dataFromSF = await getMetaDataFromSalesForce(table)
        // Extract the parts I actually need
        const relevantBits = dataFromSF.filter(field => field.name === label)
        //Create a new list in the db
        const createResult = await List.create( { name: createListName, values: relevantBits } )
        return createResult
    }
    

    it's just await Promise.all(pops.map(processData));