Firestore无法向集合新增文档 无报错但数据未写入如何解决?
问题排查方案
then用法错误:你当前写的.then(alert('xxx'))是同步执行弹窗,并不是等Firestore的写操作完成后才触发,相当于你还没收到服务端返回结果就弹出了成功提示,此时写请求可能还没发出去,如果后续有页面跳转、组件卸载等操作都会直接中断请求,需要改成.then(() => alert('xxx'))把弹窗逻辑放在回调函数里。- 缺少错误捕获:你用了async/await语法但没有包裹try/catch,promise链也没有加catch回调,自然看不到底层抛出的错误,加上错误捕获后打印日志就能快速定位是参数问题、权限问题还是配置问题。
- 检查Firestore安全规则:Firestore默认安全规则禁止所有未认证读写,先确认你的规则是否放开了已认证用户对
postData集合的写权限,测试阶段可以临时放开所有读写权限验证逻辑,验证通过后再改回严格规则即可。 - 检查Firebase初始化配置:确认
initFirebase文件里的项目配置正确,且已经导入了firebase/firestore模块,很多场景下初始化只导入了auth模块没导入firestore,也会导致操作静默失败。 - 增加session存在性判断:你直接使用了
session.user.name,如果用户未登录session为null时会直接抛出异常,加上非空判断可以避免这类逻辑错误。
修复后代码示例
import styles from '../../styles/createPost.module.css' import firebase from '../../firebase/initFirebase' import { useSession } from 'next-auth/client' export default function CreatePostButton(props) { const [session] = useSession() const time = Date.now() const today = new Date(time) const sendData = async() => { // 提前判断用户登录状态 if (!session?.user) return try { if (props.postContent) { await firebase.firestore().collection("postData").doc() .set({ postAuthor: session.user.name, path: "/cidProfile", profileImg: session.user.image, postText: props.postText, postContent: props.postContent.name, postTime: today.toUTCString(), reactionsTotal: 1, isliked: false, commentCount: 0, shareCount: 0, sharable: props.shareable, }) // 写操作完成后再弹提示 alert('Your Post was Sent!') } else { await firebase.firestore().collection("postData").doc() .set({ postAuthor: session.user.name, path: "/meow", profileImg: session.user.image, postText: props.postText, postTime: today.toUTCString(), reactionsTotal: 1, isliked: false, commentCount: 0, shareCount: 0, sharable: props.shareable, }) alert(props.postText) } } catch (e) { // 打印错误信息排查问题 console.error('Firestore写操作失败: ', e) alert('发布失败,请重试') } } return ( <div className={styles.postButtonDiv}> <button className={styles.postButton} onClick={sendData} disabled={!props.disableButton}>Post</button> </div> ) }
内容的提问来源于stack exchange,提问作者Justin
相关产品推荐
相关产品推荐

