簡體   English   中英

計算節點js和mongodb中的訂單總價

[英]Calculate order total price in node js and mongodb

我用Node JS和MongoDB構建了一個訂購系統,我想在服務器中計算訂單total_price ,然后將其保存為新訂單,

let ref = (model) => {
  return { type: mongoose.Schema.Types.ObjectId, required: true, ref: model };
};

這是我的order model 架構

{
  items: [
    {
      id: ref("menu_item"),
      count: String,
      size: String,
      options: [String],
    },
  ],
  total_price: String,
  tip: String,
};

這是 menu_item menu_item模式

{
  name: String,
  price: String,
  vat: String, // 3%
  size: [
    {
      name: String,
      unit: String,
      price: String,
      vat: String, // 3%
      in_stock: Boolean,
      is_default: Boolean,
    },
  ],
  options: [
    {
      title: String,
      options: [
        {
          name: String,
          price: String,
          vat: String, // 3%
          in_stock: Boolean,
          is_default: Boolean,
        },
      ],
    },
  ],
}

怎么可能? 這是我做過的一些嘗試,但這是錯誤的方式。

當客戶發送訂單時,將調用此 function

async (req, res) => {
      let total = 0;
      let size_price = 0;
      let options_price = 0;
      
      let {
        items,
        tip,
      } = req.body;

      let price = 0;
      let item_price = items.forEach(async (el) => {
        let menu_item = await req.models.menu_item.findOne({ _id: el.id });
        price += parseInt(menu_item.price);
        console.log(menu_item.price) // first 12 second 9
        console.log(price) // first 12 second 21
      });
      

      console.log(price) // return 0
}

forEach循環在執行下一次迭代/退出循環之前不會等待異步函數完成。 為了等到從數據庫中查詢到所有記錄並更新price值,我們可以將所有承諾包裝在Promise.all中,或者在for-of循環中連續執行它們。

這是使用Promise.all的更新代碼:

async (req, res) => {
      let total = 0;
      let size_price = 0;
      let options_price = 0;
      
      let {
        items,
        tip,
      } = req.body;

      let price = 0;
      await Promise.all(items.map(async (el) => {
          let menu_item = await req.models.menu_item.findOne({ _id: el.id });
          price += parseInt(menu_item.price);
          console.log(menu_item.price) // first 12 second 9
          console.log(price) // first 12 second 21
        })
      );
      

      console.log(price) // return 0
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM