簡體   English   中英

我該如何解決 FirebaseError:collection() 的預期第一個參數是 CollectionReference、DocumentReference 或 FirebaseFirestore

[英]How can i solve FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

我正在嘗試更新 firestore 集合文檔中的字段值。 但它給了我這個錯誤。

“FirebaseError:collection() 的第一個參數應為 CollectionReference、DocumentReference 或 FirebaseFirestore”

這是我的代碼

const Post = ({ name, description, message, photoUrl, like, id }) => {

    const usersCollection = collection(database, 'posts');
    const searchQuery = query(usersCollection, where(documentId(), '===', id))

    const handleLike = async () => {
        // eslint-disable-next-line no-unused-vars
        const update = await updateDoc(doc(searchQuery), {
            like: like + 1,
        })
    }
    return (
        <div className="Post">
            <div className="post__header">
                <Avatar />
                <div className="post__info">
                    <h2>{name}</h2>
                    <p>{description}</p>
                </div>
            </div>

            <div className="post__body">
                <p>{message}</p>
            </div>

            <div className="post__buttons">
                <span onClick={handleLike}>
                    <InputOpntion
                        Icon={ThumbUpOffAltIcon}
                        title="Like"
                        color="gray"
                        like={like} />
                </span>
                <InputOpntion
                    Icon={ChatOutlinedIcon}
                    title="Comment"
                    color="gray" />
                <InputOpntion
                    Icon={ShareOutlinedIcon}
                    title="Share"
                    color="gray" />
                <InputOpntion
                    Icon={SendOutlinedIcon}
                    title="Send"
                    color="gray" />
            </div>
        </div>
    );
};

export default Post;

updateDoc()函數將DocumentReference作為參數而不是Query 由於您已經有了要更新的文檔的 ID,因此無需先通過查詢獲取文檔然后再更新它們。 嘗試重構代碼,如下所示:

const usersCollection = collection(database, 'posts');

// Create DocumentReference to that post document
const docRef = doc(usersCollection, id);

const handleLike = async () => {
    // Pass the DocRef here
    const update = await updateDoc(docRef, {
        like: like + 1,
    })
}

暫無
暫無

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

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