Home > database >  Update and get lastest data in one function
Update and get lastest data in one function

Time:01-21

I have the following javaScript code for Nodejs to update data in MongoDB.

I have a list of products that I want update (called itemsToBeUpdated). (Update the preference value in the order that they are passed-in)

Once all the updates have been completed, I would like to go and retrieve the product list by calling the function getProducts(req, res);

where should I put the getProducts(req, res)? Not position A because Product.findByIdAndUpdate is async so it will get to position A before the findByIdAndUpdate is completed. Not position B because there are more items to loop through.

const updateAndRefreshProducts = (req,res) => {
    
    const itemsToBeUpdated = req.body;

    const counter = someValue

    for(let i = 0; i<itemsToBeUpdated.length; i  ){

            const newPreference = counter;
            counter  ;

            condition= {_id: itemsToBeUpdated[i]._id};


            Product.findByIdAndUpdate(condition, {preference:newPreference})
                .then(result => {
                    console.log('performing update completed for result'   result.name  " : ", result.preference);
                    //position B 
                })
                .catch(error =>{
                        console.log('error', error);
                });

            
    }
    
    //position A
}

thanks

CodePudding user response:

There are a couple of way to handle this, the easiest way to accomplish this will be to utilize Promise.all().

You may want to read on this documentation

const updateAndRefreshProducts = (req,res) => {
    
    const itemsToBeUpdated = req.body;
    const productUpdatePromises = []
    const counter = someValue

    for(let i = 0; i<itemsToBeUpdated.length; i  ){
            const newPreference = counter;
            counter  ;
            condition= {_id: itemsToBeUpdated[i]._id};
            const productUpdatePromise = Product.findByIdAndUpdate(condition{preference:newPreference})
            productUpdatePromises.push(productUpdatePromise)    
    }
    
  await Promise.all(productUpdatePromises).then((results) => {
    console.log(results);
    //Called your get all products here
  })
  .catch((error) => {
    console.error(error.message);
  });
}
  • Related