0

I'm trying to create / stage a schedule for a card tournament which would consist of a set of documents (one for each week a game is played) with a weekId and Date on each in MongoDB. My interface requires two pieces of user input data to accomplish this - number of weeks, and a starting date. From there it uses an async forEach loop to create "x" number of weeks worth of documents in the database. This approach seems to work partially, however, I get a random number of documents that actually get created in MongoDB (the number of documents that actually get reliably created vary in two environments - I can get up to 10 reliably on my dev workstation, but not so on a micro cloud instance on Linode). It seems as though some of the promises are being dropped, or the network cannot keep up with the number of documents I need to create. For instance on my local Mac. I can do 10 no problem. If I increase the number to 20 weeks, I sometimes get 19, sometimes 16, etc., but never 20. If I increase the number to 25, I get over 20, but never 25. In the cloud I can't even get 10 to propagate to the database successfully. I've tried numerous ways to code around the issue, but can't seem to find an adequate solution to getting all the documents in the database. What I'm hoping is someone can look at my code and not necessarily try and figure out exactly what it is doing, but rather, see if there's anything I can do with Axios promises to synchronize these request so they all make it to the database. Note I've tried several ways to accomplish this. This latest example probably has what is an extraneous call to the sendSchedule function, but I was trying to mimic a "web helper" pattern that I had found here on stackoverflow.

Here's my latest code to do this (vue):

    import { api } from "../../helpers/helpers";

     createOrUpdate: function(weeksArr, firstDate, startDate, days) {
          weeksArr.forEach(async week => {
            let schedule = {};
            if (week === 1) {
              schedule.weekId = 1;
              schedule.gameDate = firstDate;
            }
            if (week > 1) {
              schedule.gameDate = startDate.setDate(startDate.getDate() + days);
              schedule.weekId = week;
            }
            const res = await api.createSchedule(schedule);
            console.log(res);
          });

    ------

    helpers.js

    export const api = {
    createSchedule: (async function(schedule) {
            let returnData = await sendSchedule(schedule)
            return returnData
        })
    }

   const sendSchedule = handleError(async payload => {    
        const res = await axios.post(createScheduleURL, payload);    
        return res.data;  
    });
adamfhelm
  • 35
  • 8

0 Answers0