2017-04-19 48 views
0

我有一個名爲Cart的客戶端端本地集合,其中包含產品對象。我想要做的是將模板中所有產品和數量的總和返回到模板中。我這樣做如下:流星Mongo.Cursor#地圖沒有預期的效果

Template.layout.helpers({ 

    cartTotal:() => { 
    if(!Cart.findOne({})) { 
     return 0; 
    } 
    else { 
     let productsCursor = Cart.find({}); 
     let totalPrice = 0; 

     productsCursor.map((product) => { 
     let subtotal = product.qty*product.price; 
     totalPrice =+ subtotal; 
     console.log(totalPrice); 
     }); 

     return totalPrice.toFixed(2); 
    } 
    } 
}); 

一切都很好地總結時,我將同樣的產品以集合(該product.qty增加1),但是當我添加另一個目的是在Cart集合,它開始總結只有這個物體的數量和價格。

如果我在瀏覽器控制檯上檢查集合,所有對象都在那裏,但cartTotal方法的結果未返回正確的值。

我已經試過使用Mongo.Cursor#forEach()方法,但結果是一樣的。我怎樣才能達到我想要做的?哪裏不對???

回答

0

這可能與反應性有關。直接嘗試繪製光標,而不是將其保存爲一個變量,如下所示:

Template.layout.helpers({ 

    cartTotal:() => { 
    if(!Cart.findOne({})) { 
     return 0; 
    } 
    else { 

     let totalPrice = 0; 

     Cart.find({}).map((product) => { 
     let subtotal = product.qty*product.price; 
     totalPrice =+ subtotal; 
     console.log(totalPrice); 
     }); 

     return totalPrice.toFixed(2); 
    } 
    } 
}); 
+0

遺憾的是它不工作... :(不過感謝您的回答。 – kemelzaidan

0

我不知道究竟這是不是在minimongo或巴貝爾的一個bug,但totalPrice = totalPrice + subtotal;替代totalPrice =+ subtotal;工作。

0

您的代碼和答案的代碼之一包含=+

不是一個驚喜,你得到的總價格只有一個產品,因爲你不調整價格,但在每次迭代改寫:

// let total price be the subtotal with positive sign 
totalPrice = +subtotal; 

你一定意味着+=,這是不一樣。

我鼓勵你嘗試功能方法:

Template.layout.helpers({ 
    cartTotal() { 
    Cart.find() 
    .map(product => product.qty * product.price) 
    .reduce((prev, curr) => prev + curr, 0) 
    .toFixed(2); 
    } 
});