我正在做一个购物车,我必须获得产品的价格才能乘以数量,但我遇到了异步问题,我无法在循环的每次迭代中获得价格。
router.get('/cartlist', function(req, res) {
var db = req.db;
var collection = db.get('cart');
collection.find({},{},function(e,docs){
var totalPrice = 0;
for(var i in docs)
{
var name = docs[i].productname;
var amount = docs[i].amount;
var products = db.get('products');
var idPrice = 0;
getPrice(products, name, function(data)
{
idPrice = data;
});
console.log(idPrice);
}
totalPrice += idPrice * amount;
console.log(totalPrice);
res.render('cartlist', {
"cartlist" : docs
});
});
});
回调:
function getPrice(collection, name, callback)
{
collection.findOne({"productname" : name}, {_id:0, price:1}, function(err, objs)
{
if(objs != null)
{
callback(objs.price);
}
});
}
当我显示totalPrice的值为0时,我该怎么做?我需要获取价格才能在循环中执行 totalprice += amount * price 。谢谢。
最佳答案
假设您的购物车和产品系列具有以下最低架构:
购物车
- productname (reference to product collection on productname field)
- amount
产品
- productname
- price
然后,使用聚合框架并运行采用 $lookup
运算符的管道,以对同一 products
集合执行左外连接会更容易、更高效数据库过滤来自“加入”集合的文档进行处理,然后使用 $group
和 $sum
运算符在 $multiply
管道中计算总价.
下面的例子展示了你如何去做这件事
router.get('/cartlist', function(req, res) {
var db = req.db;
var collection = db.get('cart');
collection.aggregate([
{
"$lookup": {
"from": "products",
"foreignField": "productname",
"localField": "productname",
"as": "productList"
}
},
{ "$unwind": "$productList" },
{
"$group": {
"_id": null,
"totalPrice": {
"$sum": {
"$multiply": [
"$productList.price",
"$amount"
]
}
},
"cartlist": { "$push": "$$ROOT" }
}
}
], function(err, result){
console.log(result);
console.log(result[0]);
console.log(result[0].totalPrice);
res.render("cartlist", result);
});
});
关于javascript - 在 MongoDB 中获取查询外的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40962057/