我有 IndexedDB 表
"00014381104394"
{id: "00014381104394", name: "A House Divided: Season 1 (DVD)", productimg: "http://i5.walmartimages.com/asr/99cfec5c-634e-4e26…4465.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", unitofissue: "each", quantity: 1, …}
1 "00016500590958"
{id: "00016500590958", name: "One A Day Men's 50+ Mini Gels, Multivitamins for Men, 80 Ct", productimg: "http://i5.walmartimages.com/asr/7d44d419-bd6f-4808…b7ea.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", unitofissue: "each", quantity: 1, …}
2 "00022141041599"
{id: "00022141041599", name: "Mepps Dressed Aglia Inline Spinner, Silver & Gray, 1/4 oz", productimg: "http://i5.walmartimages.com/asr/a0ce2579-300a-4536…0d63.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", unitofissue: "each", quantity: 1, …}
3 "00038257767124"
{id: "00038257767124", name: "Hanes Men' Max Cushion Comfort Top B&T Crew Socks 6 Pack", productimg: "http://i5.walmartimages.com/asr/f439dc53-c905-45bb…3436.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", unitofissue: "each", quantity: 1, …}
4 "00041333002132"
{id: "00041333002132", name: "Duracell Coppertop AAA Battery, Long Lasting Triple A Batteries, 24 Pack", productimg: "http://i5.walmartimages.com/asr/09b2aa97-6655-4422…2259d.png?odnHeight=180&odnWidth=180&odnBg=ffffff", unitofissue: "each", quantity: 1, …}
我需要更新每个项目的数量,所以我尝试了下面的代码
db.cartitems.get(newItemId)
.then((result) => {
if (result){
db.table("cartitems").toArray().then((cartitemArry) => {
var cartitemArry1 = []
cartitemArry.forEach(product => {
if (product.id == newItemId){
// increase item quantity
var qty = parseInt(product["quantity"])+1
product["quantity"] = qty
console.log(product.id," was found in cart. Qty increased from ",qty, "to ", product["quantity"])
cartitemArry1.push(product)
console.log("cart array push at ",newItemId,"\n", cartitemArry1)
}else{
cartitemArry1.push(product)
}
console.log("cart array", cartitemArry1)
});
db.table('cartitems').bulkPut(cartitemArry1)
.then(() =>{
console.log('finished updating cart')
}).catch(error => {
console.log(error);
});
resolve(cartitemArry1)
})
上面的代码获取表中的所有项目,但不保存更新的数量。我只想能够增加或减少指定项目ID的数量。我不知道如何直接更新特定项目ID的属性。因此,我先获取所需的项目,然后获取存储中的所有项目,并使用存储中的所有项目创建一个新数组,以包括所需项目的更新数量,然后执行bulkPut到同一个存储中。-实现这一点的最佳方法是什么?
1条答案
按热度按时间w8f9ii691#
如果您只想增加cartitem中给定newItemId的“quantity”属性,请执行以下操作:
您也可以这样做(相当于上面的代码):
参见文档:
Table.get()
Table.put()
Collection.modify()