【问题标题】:Saving the document id at the time of creating a document in Firebase v9 using React JS在使用 React JS 在 Firebase v9 中创建文档时保存文档 ID
【发布时间】:2021-10-01 05:45:45
【问题描述】:

您好,我希望在创建新文档时,在“projectId”处将自动生成的文档的 id 传递给“projectId”字段,这可能吗?

这是我的代码:

addDoc(collection(db, "projects"), {
        name: project,
        uid: currentUser,
        projectId: 'here the proyectId that i dont know how to pass it'
        
        
      })

我正在使用 Firebase v9 Modular、Firestore 和 React JS

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    以下方法可以解决问题:

    import { collection, doc, setDoc } from "firebase/firestore"; 
    
    // Add a new document with a generated id
    const newDocRef = doc(collection(db, "projects"));
    
    // Set the doc, using the id property of the DocumentReference
    await setDoc(newDocRef, {
        name: project,
        uid: currentUser,
        projectId: newDocRef.id
      }
    );
    

    【讨论】:

    • 谢谢!一直在寻找那个?
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 2022-08-17
    • 2022-06-11
    • 2019-12-03
    • 1970-01-01
    相关资源
    最近更新 更多