【问题标题】:Firestore setDoc Function not merging new items on React JSFirestore setDoc 函数不在 React JS 上合并新项目
【发布时间】:2023-02-14 11:28:49
【问题描述】:

所以我试图让这个功能“Walletwrite”检查文档是否已经存在,如果文档不存在,则创建一个包含我想要添加的值的新文档,或者通过添加一个新字段来更新现有文档那些新的价值观。所有这些都在 React JS 上。

但是,如果文档已经存在,我的 setDoc 函数实际上会覆盖现有数据。

关于问题出在哪里的任何想法?

async function Walletwrite() {
        //These first 2 consts check if the entry is already in that specific document to prevent duplicates.
        const marketRef = db.collection("marketplace");
                const query = marketRef.where("wallet", "array-contains", account).where("item", "==", item.id).limit(1);
                
                query.get().then((snapshot) => {
                    if (snapshot.empty == false) {
                        console.log(snapshot)
                        return
                        
                        }
        
                        else{
                        
                              //This is where it gets tricky and merge: true is not working

                                const walletRef = doc(db, 'marketplace', item.id);
                               setDoc(walletRef, {item: item.id, wallet: account} , { merge: true });
                    
                             
                           
                        }
                            });
                        
    }

尝试不同的 firestore 函数,但它们似乎都不适合我的用例,除了这个 setDoc with merge: true..

【问题讨论】:

    标签: javascript reactjs database firebase google-cloud-firestore


    【解决方案1】:

    我还注意到 merge: true 仍然覆盖旧文档,这听起来像是一个错误。

    您可以使用 updateDoc 函数来缓解它,但文档必须存在才能使用此函数。所以在你的情况下:

    const walletRef = doc(db, 'marketplace', item.id);
    
    const walletData = {item: item.id, wallet: account}
    
    const walletSnapshot = getDoc(walletRef)
    
    if (walletSnapshot.exists()) {
      updateDoc(walletRef, walletData);
    } else {
      addDoc(collection(db, 'marketplace', walletData), 
    }
    

    不理想,但现在应该这样做......

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2019-01-02
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2020-06-26
      • 2022-11-18
      • 1970-01-01
      相关资源
      最近更新 更多