React JS中Firestore v9版本如何向子集合写入数据
Firestore v9 版本对应实现代码
首先需要提前从firebase/firestore模块导入所需的工具方法,确保你已经正确初始化了Firestore并导出了db实例:
// 导入依赖 import { collection, addDoc, serverTimestamp } from 'firebase/firestore'; // 引入你自己初始化完成导出的db实例 import { db } from './你的firebase配置文件路径';
改写后的写入代码如下:
addDoc(collection(db, "rooms", channelId, "messages"), { message: input, timestamp: serverTimestamp(), user: 'Apollos', userImage: 'https://naniwallpaper.com/files/wallpapers/eren-yeager/1-EREN%20YEAGER-1080x1920.jpg' });
如果需要捕获异常或者获取新增文档的自动生成ID,可以使用异步写法:
const submitMessage = async () => { try { const newDocRef = await addDoc(collection(db, "rooms", channelId, "messages"), { message: input, timestamp: serverTimestamp(), user: 'Apollos', userImage: 'https://naniwallpaper.com/files/wallpapers/eren-yeager/1-EREN%20YEAGER-1080x1920.jpg' }); // 可通过newDocRef.id获取自动生成的文档ID } catch (err) { console.error('消息写入失败:', err); } }
说明:Firestore v9采用模块化API设计,
collection()方法支持传入多级路径参数直接定位到目标子集合,无需逐层链式调用,addDoc()方法对应旧版本的.add()方法,用于在指定集合下新增带自动生成ID的文档。
内容的提问来源于stack exchange,提问作者Swift
相关产品推荐
相关产品推荐

