简体   繁体   English

反应 Firestore 查询嵌套集合 where 字段然后更新,或添加新文档

[英]react Firestore query nested collection where field then update, or add new doc

I'm currently ripping my hair out trying to query a nested collection in my Firestore db.我目前正在尝试查询我的 Firestore 数据库中的嵌套集合。

my db is set up as follows:我的数据库设置如下:

  users (collection)
    - username
    - displayName
    - ratedItems (collection)
            - itemId
            - timestamp
            - likedItem

I want to be able to add/update the rated item in the ratedItems collection for a specific user but I seem to be hitting 2 problems:我希望能够为特定用户添加/更新ratedItems 集合中的评级项目,但我似乎遇到了两个问题:

  1. I assume the query is incorrect as if(querySnapshot.empty) always returns false even if there are no matching items (matching the itemId) in the ratedItems collection, so it always attempts to add a new item which results in duplicate entries in the collection.我假设查询不正确,因为 if(querySnapshot.empty) 总是返回 false,即使在ratedItems 集合中没有匹配的项目(与 itemId 匹配),所以它总是尝试添加一个新项目,这会导致集合中的重复条目.

  2. if I force the code to bypass the conditional it throws an error when it attempts to update the existing item:如果我强制代码绕过条件,它会在尝试更新现有项目时引发错误:

Expected type 'mc', but it was: a custom yc object

My thoughts are I am using the collectionGroup query incorrectly but I haven't found a solution for this yet.我的想法是我错误地使用了 collectionGroup 查询,但我还没有找到解决方案。 Should I even be using collectionGroup at all??我什至应该使用 collectionGroup 吗? from what I've read, if I understand correctly this will query every ratedItem collection regardless of the user, which isn't what I want从我读过的内容来看,如果我理解正确,这将查询每个ratedItem 集合,而不管用户如何,这不是我想要的

 const rateItem = async (itemId, liked) => {
    try {
      const itemRef = collection(db, 'users', currentUser.uid, 'ratedItems');
      const q = query(
        collectionGroup(db, 'users', currentUser.uid),
        where('itemId', '==', itemId)
      );
      const querySnapshot = await getDocs(q);

      if (querySnapshot.empty) {
        await addDoc(itemRef, {
          itemId: itemId,
          timestamp: serverTimestamp(),
          likedItem: liked,
        });
      } else {
        await updateDoc(itemRef, {
          timestamp: serverTimestamp(),
          likedItem: liked,
        });
      }
    } catch (err) {
      console.log(err.message);
    }
  };

I assume the query is incorrect as if(querySnapshot.empty) always returns false even if there are no matching items (matching the itemId) in the ratedItems collection, so it always attempts to add a new item which results in duplicate entries in the collection.我假设查询不正确,因为 if(querySnapshot.empty) 总是返回 false,即使在ratedItems 集合中没有匹配的项目(与 itemId 匹配),所以它总是尝试添加一个新项目,这会导致集合中的重复条目.

You used the itemRef for both of addDoc and updateDoc which is not the proper way to do it.您对addDocupdateDoc都使用了itemRef ,这不是正确的方法。 You need a correct query syntax in order to update your Firestore document.您需要正确的查询语法才能更新您的 Firestore 文档。

if I force the code to bypass the conditional it throws an error when it attempts to update the existing item如果我强制代码绕过条件,它会在尝试更新现有项目时引发错误

You can try the code below to update your nested document:您可以尝试以下代码来更新您的嵌套文档:

const updateitemRef = query(
    collection(db, 'users', 'user_item', 'ratedItems'), 
    where('itemId', '==', itemId)
);

const itemSnapshot = await getDocs(updateitemRef);

itemSnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots 
    updateDoc(doc.ref, {
        likedItem: liked,
        timestamp: serverTimestamp()          
    });
});  

For the complete code, you can try the code below:对于完整的代码,你可以试试下面的代码:

const rateItem = async (itemId, liked) => {
    try {
        const q = query(
            collectionGroup(db, 'users', currentUser.uid),
            where('itemId', '==', itemId)
        );
        const querySnapshot = await getDocs(q);

        const additemRef = collection(db, 'users', currentUser.uid, 'ratedItems');

        const updateitemRef = query(
            collection(db, 'users', currentUser.uid, 'ratedItems'), 
            where('itemId', '==', itemId)
        );
        const itemSnapshot = await getDocs(updateitemRef);

        if (querySnapshot.empty) {
            await addDoc(additemRef, {
                itemId: itemId,
                likedItem: liked,
                timestamp: serverTimestamp()
            });
        } else {
            itemSnapshot.forEach((doc) => {
            // doc.data() is never undefined for query doc snapshots 
                updateDoc(doc.ref, {
                    likedItem: liked,
                    timestamp: serverTimestamp()          
                });
            });      
        }
    } catch (err) {
        console.log(err.message);
    }
};

For more references in creating a query, you can refer to the guides below:有关创建查询的更多参考,您可以参考以下指南:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 React 中添加带有嵌套集合的新 Firestore 文档? - How to add a new Firestore document with a nested collection in React? 使用firestore在集合中添加/更新数组并做出本机反应 - add/update array in collection with firestore and react native Firestore文档ID以查询更新 - Firestore doc ID to query update 除非我先刷新,否则反应应用程序中的 Firestore 文档字段更新会给出 TypeError - Firestore doc field update in react app giving TypeError unless I refresh first 在反应中读取 Firestore 子集合数据 - 如何在查询的子集合中设置父 ID - Reading firestore sub-collection data in react - how to set a parent id in the sub-collection where query TypeError: (0 , _firestore.default)(...).collection(...).doc(...).add 不是函数 - TypeError: (0 , _firestore.default)(...).collection(...).doc(...).add is not a function 如何连续将对象添加到 Firestore 中的嵌套集合 - How to continuously add objects to nested collection in Firestore 如何在firestore中查询同一集合上的多个字段 - How to query multile field on same collection in firestore Firestore 云功能更新所有文档中的字段与参数 - Firestore cloud-function to update a field in all doc in coll with parameter 如何对嵌套文档进行查询存储。 Firebase Node.js - How to firestore query on nested doc. Firebase Nodejs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM