skip to Main Content

so im creating instagram clone and in the firebase docs trying to update the fields:

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

this is my firebase database picture:
enter image description here

I want my code to create a collection of "post" for every user with the fields i added.

EDITED: This is the screenshot i got after adding catch
pic

AGAIN EDITED: USERID

Again::: enter image description here

Security Rule Code:

       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();
        }
     }
      }

2

Answers


  1. The setDoc() takes a DocumentReference as first parameter and a single object containing all the fields of your document as second. Try refactoring the code as shown below:

    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()
        }
      );
    };
    
    Login or Signup to reply.
  2. I want my code to create a collection of "post" for every user with
    the fields I added.

    You need to use the ID of the user to add a post document in a subcollection, as follows:

      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()
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search