簡體   English   中英

如何在 reactJs 中更新 V9 firebase 上子集合的所有字段

[英]how to update sub collection's all fields on V9 firebase in reactJs

所以我正在創建 instagram 克隆並在 firebase 文檔中嘗試更新字段:

 const uploadPostOnline = (imageUrl, caption) => {
  const userRef = doc(db, "users", "posts");
  setDoc(
    userRef,
    { imageUrl: imageUrl },
    { caption: caption },
    { likes: 0 },
    { likesByUsers: [] },
    { comments: [] },
    { createdAt: serverTimestamp() },
    {}
  );
};

這是我的 firebase 數據庫圖片: 在此處輸入圖像描述

我希望我的代碼使用我添加的字段為每個用戶創建一個“帖子”集合。

編輯:這是我添加 catch 后得到的截圖圖片

再次編輯: 用戶身份

再次::: 在此處輸入圖像描述

安全規則代碼:

       rules_version = '2';
     service cloud.firestore {
      match /databases/{database}/documents {
         function userIsAuthenticated(){
        return request.auth != null;
      }
       match /{path=**}/posts/{postId}{
        allow read, write : if userIsAuthenticated();
             }
        match /users/{userId}{
           allow read, write : if userIsAuthenticated();
        }
     }
      }

我希望我的代碼使用我添加的字段為每個用戶創建一個“帖子”集合。

您需要使用用戶的ID在子集合中添加post文檔,如下:

  const userId = ...  // For example auth.currentUser.uid (check that value is not undefined, see https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user)
  const collectionRef = collection(db, "users", userId, "posts");
  addDoc(collectionRef, {
      imageUrl, 
      caption,
      likes: 0,
      likesByUsers: [],
      comments: [],
      createdAt: serverTimestamp()
    });

setDoc()DocumentReference作為第一個參數,將包含文檔所有字段的單個object 作為第二個參數。 嘗試重構代碼,如下所示:

const uploadPostOnline = (imageUrl, caption) => {
  const userRef = doc(db, "users", "posts");
  setDoc(
    userRef, {
      // 'imageUrl: imageUrl' is redundant as your property name and var name are name
      imageUrl, 
      caption,
      likes: 0,
      likesByUsers: [],
      comments: [],
      createdAt: serverTimestamp()
    }
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM