mongoose 当i将值推入空数组时,它显示节点js

9w11ddsr  于 2023-02-04  发布在  Go
关注(0)|答案(2)|浏览(140)
exports.OrderPlace = (req, res) => {
  const all_product = req.body.product_info;
  let meta = [];
  all_product.forEach((element) => {
    Ticket.find({ _id: element.product_id }, function (err, docs) {
      if (err) return handleError(err);
      if (docs[0]._id == element.product_id) {
        if (element.quantity < docs[0].quantity) {
          meta.push({
            cart_id: element.id,
            pro_id: element.product_id,
            quantity: element.quantity + " Asking quentity is not available!",
          });
        }
      }
    });
  });
  console.log(meta);
};

我正在尝试推送cart_idpro_idquantity .它正在记录我的空值,请帮助
我期望console.log(meta)值,如

[
    {
        cart_id: "63db8665ba7126c2b35fb231",
        pro_id: "63d025a8eefcf49cdcdd5472",
        quantity: "36 Asking quentity is not available!",
    },
    {
        cart_id: "63dbc2a7fbf7daf48052189e",
        pro_id: "63ce4393c3433881173d1502",
        quantity: "40 Asking quentity is not available!",
    }
]
tnkciper

tnkciper1#

将整个代码块封装在一个异步函数中,并在函数中使用await来等待Ticket.find操作的结果。

exports.OrderPlace = async (req, res) => {
  const all_product = req.body.product_info;
  let meta = [];
  let flag = "";

  for (const element of all_product) {
    const docs = await Ticket.find({ _id: element.product_id }).exec();
    if (docs[0]._id == element.product_id) {
      if (element.quantity > docs[0].ticket_quantity) {
        flag = "false";
        meta.push({
          cart_id: element.id,
          pro_id: element.product_id,
          quantity: element.quantity + " Asking quentity is not available!",
        });
      }
    }
  }
  console.log({ flag: flag, meta });
};
xxe27gdn

xxe27gdn2#

我发现操作对象数组最简单的方法是使用数组方法,如filter、map等...
下面的代码可能会帮助您

exports.OrderPlace = (req, res) => {
  const all_product = req.body.product_info;
  let meta = [];
  all_product.forEach((element) => {
    Ticket.find({ _id: element.product_id }, function (err, docs) {
      if (err) return handleError(err);

      element = element.filter((item) => {
          return (docs[0]._id == element.product_id && element.quantity < docs[0].quantity)
      })

      meta = element.map((item) => {
            return {
                cart_id: element.id,
                pro_id: element.product_id,
                quantity: element.quantity + " Asking quentity is not available!",
            }
      });
    });
  });
  console.log(meta);
};

相关问题