简体   繁体   中英

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

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

火力地堡集合

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

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 eg { comment: "test", userId: "1324" } .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM