nodejs和mongodb中计算订单总价 [英] Calculate order total price in node js and mongodb

查看:98
本文介绍了nodejs和mongodb中计算订单总价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Node JS 和 MongoDB 构建了一个订购系统,我想在将其保存为新订单之前计算服务器中的订单 total_price

I built an ordering system with Node JS and MongoDB, I want to calculate order total_price in server before save it as a new order,

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

这是我的order模型架构

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

这是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,
        },
      ],
    },
  ],
}

怎么可能?这是我做过的一些尝试,但方法错误.

How it's possible? this is some tried that I done but it's wrong way.

当客户发送订单时会调用此函数

when customer send an order this function will be call

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 包裹在Promise.all 中或在中串行执行它们以获取-of 循环.

forEach loop does not wait for async functions to complete before executing next iteration / exiting the loop. In order to wait till all records are queried from DB and price value is updated, we can either wrap all promises in Promise.all or execute them serially in for-of loop.

这是使用 Promise.all 更新的代码:

Here is the updated code using 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
}

这篇关于nodejs和mongodb中计算订单总价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆