Javascript 计算节点js和mongodb中的订单总价
我用Node JS和MongoDB构建了一个订购系统,我想在服务器上计算订单Javascript 计算节点js和mongodb中的订单总价,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我用Node JS和MongoDB构建了一个订购系统,我想在服务器上计算订单总价,然后保存为新订单 let ref = (model) => { return { type: mongoose.Schema.Types.ObjectId, required: true, ref: model }; }; 这是我的订单模型模式 { items: [ { id: ref("menu_item"), count: String,
总价
,然后保存为新订单
let ref = (model) => {
return { type: mongoose.Schema.Types.ObjectId, required: true, ref: model };
};
这是我的订单
模型模式
{
items: [
{
id: ref("menu_item"),
count: String,
size: String,
options: [String],
},
],
total_price: String,
tip: String,
};
{
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,
},
],
},
],
}
这是菜单项
模型模式
{
items: [
{
id: ref("menu_item"),
count: String,
size: String,
options: [String],
},
],
total_price: String,
tip: String,
};
{
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,
},
],
},
],
}
这怎么可能?
这是我做的一些尝试,但这是错误的方式
当客户发送订单时,将调用此函数
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更新的代码。全部:
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
}
forEach
循环在执行下一次迭代/退出循环之前不会等待异步函数完成。为了等待数据库查询所有记录并更新price
值,我们可以将所有承诺包装在Promise.all
中,或者在for of
循环中连续执行它们
以下是使用Promise更新的代码。全部:
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
}