繁体   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