[英]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.我正在尝试更新 firestore 集合文档中的字段值。 But its giving me this error.
但它给了我这个错误。
"FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"
“FirebaseError:collection() 的第一个参数应为 CollectionReference、DocumentReference 或 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 . updateDoc()
函数将DocumentReference作为参数而不是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.由于您已经有了要更新的文档的 ID,因此无需先通过查询获取文档然后再更新它们。 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,
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.