0

I have the following function involving mongoose:

  let username = userObject.username;
  Purchase.find({
    account: username,
    fufilled: true 
  })
    .populate("keys")
    .exec(function(err, foundPurchases) {
      if (err) {
        return inStockItems;
      } else {
        if (foundPurchases.length === 0) {
          return inStockItems;
        } else {
          // these lists will be a list of IDs of game detail entries in the database
          let listOfReceivedIds = foundPurchases.keys.map(obj => obj.game);

          for (let i = 0; i < inStockItems.length; i++) {
            if (inStockItems.length <= minimum) {
              return inStockItems;
            }

            let currentProductAnalysing = inStockItems[i];
            if (listOfReceivedIds.includes(currentProductAnalysing._id)) {
              console.log("removing product");
              inStockItems.splice(i, 1);
            }
          }
          return inStockItems;
        }
      }
    });

I am running the function like the following, which returns undefined

inStockItems = function_name(inStockItems, userObject, amount);

How can I rewrite the function so that the function returns the value of inStockItems and not undefined. Thanks.

  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – FZs Nov 09 '19 at 22:53

1 Answers1

0

.exec in Mongoose returns a promise of the query result if you don't give it a callback. Your function here needs to be calling .exec() and changing its return value to return something different from the function like this:

async function function_name(inStockItems, userObject, amount) {
  const foundPurchases = await Purchase.find({
      account: username,
      fufilled: true
    })
    .populate("keys")
    .exec();
  if (foundPurchases.length === 0) {
    return inStockItems;
  } else {
    let listOfReceivedIds = foundPurchases.keys.map(obj => obj.game);

    for (let i = 0; i < inStockItems.length; i++) {
      if (inStockItems.length <= minimum) {
        return inStockItems;
      }

      let currentProductAnalysing = inStockItems[i];
      if (listOfReceivedIds.includes(currentProductAnalysing._id)) {
        console.log("removing product");
        inStockItems.splice(i, 1);
      }
    }
    return inStockItems;
  }
}

The other alternative would be to pass a callback parameter to your function and call it from the exec() callback but promises are generally cleaner to work with.

Xetera
  • 1,390
  • 1
  • 10
  • 17
  • I'll check this out tomorrow, but thank you very much for your time. –  Nov 09 '19 at 22:05