首页 > 解决方案 > doc内数组中的firestore更新值

问题描述

我看了几个小时的 firestore 文档,仍然没有找到解决这个案例的方法。我需要添加一个 ammout 功能来生产我的电子商务应用程序。

数据结构:主要集合是“购物车”,文档是用户电子邮件。

这是添加或设置产品的当前代码:

import firebase from 'firebase';


export async function addToCart(userMail, itemId, name, url, price, category, type, description) {
    const ammout = 1
    const cartItem = { itemId, name, url, price, category, type, description, ammout }
    if (userMail === undefined) throw console.error('please Login');

    const userDoc = await firebase.firestore().collection("cart").doc(userMail)

    await userDoc.get().then((doc) => {
        if (doc.exists) {
            (async () => {
                    

                await userDoc.update({
                    item: firebase.firestore.FieldValue.arrayUnion(cartItem),
                })
            })()
        }
        else {
            (async () => {
                await userDoc.set({
                    item: firebase.firestore.FieldValue.arrayUnion(cartItem)
                })
            })()
        }

    })
}

标签: reactjsfirebasegoogle-cloud-firestore

解决方案


问题可能是您在同一个函数中同时使用两者awaitPromise.then()这可能会产生一些同步问题,您也不需要await填充userDoc变量,正如您在firestore 文档示例中看到的那样。

所以基本上我会async/await从你的代码中删除所有这些,因为它们并不是真正需要的,并且Promise.then()足以.get()确保你的代码中的同步性,看起来像这样:

export function addToCart(userMail, itemId, name, url, price, category, type, description) {
    const ammout = 1
    const cartItem = { itemId, name, url, price, category, type, description, ammout }
    if (userMail === undefined) throw console.error('please Login');

    const userDoc = firebase.firestore().collection("cart").doc(userMail)

    userDoc.get().then((doc) => {
        if (doc.exists) {
            userDoc.update({
                item: firebase.firestore.FieldValue.arrayUnion(cartItem),
            })
        }
        else {
            userDoc.set({
                item: firebase.firestore.FieldValue.arrayUnion(cartItem)
            })
        }

    })
}

推荐阅读