Home > OS >  How can I add a field to document from Javascript in firebase
How can I add a field to document from Javascript in firebase

Time:01-25

I'm building a basic stackoverflow clone. People can ask questions and comment that post. For that I tried to add a "comments" section in every post. So if someone comment that post comments will be in the document. But I couldn't find a way how can I achieve this. Here is the

Firebase Collection

I tried this: when I click a button, this function will get the id of that post and add a comment to that specific post. (I get the post ID from useParams). But I'm not sure how to add a field for that specific document.

  const createComment = async (author, authorId, comment) => {
    const docRef = doc(db, "posts", id);
    const docSnap = await getDoc(docRef);

    docSnap.data().comments.push(comment);
  };

CodePudding user response:

You can use updateDoc() function to update an existing document and arrayUnion() to insert a new value in an array field. Try:

const createComment = async (author, authorId, comment) => {
    const docRef = doc(db, "posts", id);

    await updateDoc(docRef, {
        regions: arrayUnion(comment)
    });
};

Checkout the documentation for more information.


arrayUnion() will add the value only if it does not exist in the array already so if multiple users try to add same comment, it'll not work with array of strings. You might have to store an object containing userId e.g. { comment: "test", userId: "1324" }.

  • Related