[英]I am trying to update a field inside a document in Firestore from ReactJS
I am trying to update a field inside a document in firestore from reactjs and its showing an error, even though others did it and it worked for them.我正在尝试从 reactjs 更新 firestore 中文档中的一个字段并显示错误,即使其他人这样做并且对他们有用。
app.js应用程序.js
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
export { auth, app, db };
postpage.js postpage.js
import { auth, app, db } from "../../firebase/config";
import { collection, getDocs, addDoc, deleteDoc, doc, updateDoc } from "firebase/firestore";
const [allPosts, setPosts] = useState([]);
const likePost = async (id, likes) => {
await updateDoc(doc(db, "posts", id), {
likes: likes + 1,
});
};
const getPosts = async () => {
const data = await getDocs(postsControllerRef);
setPosts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id
})));
setLoading(false);
};
return(
{allposts.map((post, index) => (
<button
onClick={() =>
likePost(post.postid, post.likes)
}
>Like</button>
))}
)
The id
is a number but doc()
function takes only string path segments. id
是一个数字,但doc()
function 仅采用字符串路径段。 Also, you must pass the documentId
to update a specific document.此外,您必须传递
documentId
才能更新特定文档。 Try changing the following line:尝试更改以下行:
onClick={() =>
likePost(post.id, post.likes) // pass .id and not .postid
}
If postid
is the document ID itself, then try:如果
postid
是文档 ID 本身,则尝试:
const likePost = async (id, likes) => {
await updateDoc(doc(db, "posts", String(id)), {
likes: likes + 1,
});
};
Also, as @FrankVanPuffelen commented, you can use increment()
instead as shown below:此外,正如@FrankVanPuffelen 评论的那样,您可以使用
increment()
代替,如下所示:
import { increment } from "firebase/firestore"
await updateDoc(doc(db, "posts", String(id)), {
likes: increment(1),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.