你如何计算使用Node,Async和Mongoose的范围variables的总和?
我正在尝试执行一个asynchronous数据库查找其中每个项目在数组中查找和它的价值总和。
现在我有下面的代码,只要main
函数与数据库查找位于同一个文件中就行:
// async is the async.js library // Products is a mongoose Schema var user = { cart: [11, 22, 33], orderCost = 0; } function getTotal (user, callback) { async.each(user.cart, findProduct, function (err) { if (err) { throw err; } callback(user); }); } function findProduct (skunumber, callback) { Products.findOne({sku: skunumber}, function (err, product) { user.orderCost += product.toObject().currentPrice; callback(); }); } function main () { getTotal(user); } main();
但是,我想要数据库function,在这种情况下, Products.findOne
位于不同的文件。 完成后,te findProduct
函数将不再访问user
对象,这意味着user.orderCost +=
将失败。
有一个商定的方法来避免这个问题吗? asynchronous库是否有解决这个问题的方法,或者直接在Node中有一种方法?
1)你多次查询数据库以获得结果,你可以在这样的一个查询中得到
Products.find({sku: {$in: cart}}, function (err, products) { // use for loop to get total cost here });
2)现在改变你的代码使用上面的,你可以把这个function放在任何你想要的地方,只要它有访问产品variables
function getTotal(cart,callback) { Products.find({sku: {$in: cart}, function (err, products) { // get total callback (total); }); }
3)使用它
getTotal(user.cart, function(total){ console.log(total); });
根据意见更新
为了得到相同数量的产品从数据库(因为有多个产品具有相同的SKU),如下面的购物车使用代码
Products .find({sku: {$in: cart}}) .limit(cart.length) .exec( function (err, products) { // use for loop to get total cost here });