React JS中如何获取Firebase文档的自动生成ID
获取Firebase自动分配的文档ID
下面是两种常用的获取Firebase自动生成文档ID的方法,适配不同开发场景:
1. 提前生成文档ID(适合需要预存ID的场景)
如果需要在创建文档前就拿到自动分配的ID,可先调用无参数的doc()方法生成文档引用,再从引用中提取ID:
Web SDK 示例
import { getFirestore, collection, doc, setDoc } from "firebase/firestore"; const db = getFirestore(); // 生成文档引用并提取ID const docRef = doc(collection(db, "你的集合名称")); const autoGeneratedId = docRef.id; // 使用该ID创建文档 await setDoc(docRef, { username: "测试用户", createdTime: new Date() });
2. 创建文档后获取ID
直接通过add()方法创建文档时,可从返回的文档引用中提取自动生成的ID:
Web SDK 示例
import { getFirestore, collection, addDoc } from "firebase/firestore"; const db = getFirestore(); addDoc(collection(db, "你的集合名称"), { content: "测试内容" }) .then((docRef) => { console.log("自动生成的文档ID:", docRef.id); }) .catch((error) => { console.error("创建文档失败:", error); });
Flutter 示例
import 'package:cloud_firestore/cloud_firestore.dart'; // 方式1:提前生成ID final docRef = FirebaseFirestore.instance.collection('你的集合名称').doc(); final docId = docRef.id; await docRef.set({ 'name': 'Flutter示例', }); // 方式2:创建后获取ID final docRef = await FirebaseFirestore.instance.collection('你的集合名称').add({ 'name': 'Flutter示例', }); final docId = docRef.id;
内容的提问来源于stack exchange,提问作者stacksflow
相关产品推荐
相关产品推荐

