Home > Net >  how to update sub collection's all fields on V9 firebase in reactJs
how to update sub collection's all fields on V9 firebase in reactJs

Time:10-04

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

CodePudding user response:

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

CodePudding user response:

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