简体   繁体   中英

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

I am trying to update a field's value in the doc of firestore collection. But its giving me this error.

"FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"

Heres my code

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;

The updateDoc() functions takes a DocumentReference as a parameter and not a Query . Since you already have the ID of document you are trying to update, there's no need to fetch the documents with a query first and then update those. Try refactoring the code as shown below:

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

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