0
app.get("/indsalesx/:store/:mm", (req, res) => {
  connect();
  let ddd = [];
  let staffarray = [{}];
  let store = req.params.store;
  let mm = req.params.mm;
  const SP = mongoose.model(`sales${store}`, Sales);

  let num = stafflist[store].length - 1;
 
  for (i = 0; i <= num; i++) {
    let staffname = stafflist[store][i];

    let calc = 0;
    SP.find(
      { v_salesperson: stafflist[store][i], v_month: mm },
      "v_amount",
      (err, doc) => {
        let t = doc.length - 1;
        doc.map((res) => {
          calc = calc + res.v_amount;
        });
        ddd.name = staffname;
        ddd.amount = calc;
        staffarray.push(ddd);
      }
    );
  }
  console.log(staffarray);
});

The issue I have is: Why is staffarray returning an empty array? staffarray was declared as an empty array of objects, and in a loop function, objects were pushed to to array. But when I console.log(staffarray), it returns the empty array of objects declared initially.

Any help on what to do?

0

3 Answers 3

1

When using find(), you can use 2 approaches.

  1. Pass a callback function
  2. await the function to execute and return the results.

It appears that you used the first approach which means that you are passing a callback into the find() method which handles the result once received.

The console.log() code line will execute before the result will return since it's the next line to execute after the for loop.

So, let's go through what it happening here:

  1. Javascript is executing the find() code line.
  2. That line of code is being placed in the web API which are the pieces of the browser in which concurrency kicks in and makes the call to the server for us.
  3. The console.log() line is being executed with an empty array (since the results haven't been received yet.
  4. After some time, results came back and the callback is being set in the callback queue.
  5. The JS event loop takes the callback from the callback queue and executes it.

This is part of the javascript event loop. you could read more about this here

Mongoose documentation: Model.find()

Sign up to request clarification or add additional context in comments.

Comments

0

you can use for of with async/await instead of for


app.get("/indsalesx/:store/:mm", async(req, res) => {
    connect();
    let ddd = [];
    let staffarray = [{}];
    let store = req.params.store;
    let mm = req.params.mm;
    const SP = mongoose.model(`sales${store}`, Sales);
  
    let num = stafflist[store].length - 1;
    var list = Array.from(Array(num).keys());
    for (let i of list) {
      let staffname = stafflist[store][i];
      let calc = 0;
      let doc = await SP.find(
        { v_salesperson: stafflist[store][i], v_month: mm },
        "v_amount"
      );
      let t = doc.length - 1;
      doc.map((res) => {
        calc = calc + res.v_amount;
      });
      ddd.name = staffname;
      ddd.amount = calc;
      staffarray.push(ddd);
    }

    console.log(staffarray);
  });

Comments

0

I have been able to solve it, all I needed was proper structuring with the async and await statements.

app.get("/indsalesx/:store/:mm", async (req, res) => {
  connect();
  let ddd = {};
  let staffarray = [];
  let store = req.params.store;
  let mm = req.params.mm;
  const SP = mongoose.model(`sales${store}`, Sales);

  let num = stafflist[store].length - 1;

  for (i = 0; i <= num; i++) {
    let staffname = stafflist[store][i];
    let calc = 0;
    await SP.find(
      { v_salesperson: stafflist[store][i], v_month: mm },
      "v_amount",
      (err, doc) => {
        let t = doc.length - 1;
        doc.map((res) => {
          calc = calc + res.v_amount;
        });

        staffarray.push({ name: staffname, amount: calc });
      }
    );
  }
  console.log(staffarray);
  res.send({ data: staffarray });
});


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.