【问题标题】:How to create Firestore subcollection using the new WebSDK 9?如何使用新的 WebSDK 9 创建 Firestore 子集合?
【发布时间】:2022-01-23 21:43:02
【问题描述】:

基本上我想做的就是在我的文档中创建一个子集合,但使用 webSDK 9,即可摇树的 SDK。

我找到了解决方案,但都已过时,使用旧的 sdk。

如果这有帮助,我正在使用 NextJS 和 ES6。

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore next.js


    【解决方案1】:

    您需要使用要添加子集合的 Firestore 文档的 DocumentReference,如下所示:

    const docRef = ....;
    const docSubcollectionRef = collection(docRef, 'theSubColl');
    await addDoc(docSubcollectionRef, {foo: 'bar'});
    

    更具体地说,如果您在theTempoColl 集合中有一个id 为doc1(即docRef = doc(db, 'theTempoColl', 'doc1'))的文档,则上述代码将生成一个具有以下路径的文档:theTempoColl/doc1/theSubColl/{auto_generated_Id}

    【讨论】:

      【解决方案2】:

      如果你定义了特定的文档 ID,你也可以使用 setDoc。

      import {db} from './config';
      import {setDoc, doc } from '@firebase/firestore'
      
      export default function Page(){
       const createDocWithSpecificId = async () => {
        cosnt docRef = doc(db, 'collection_name', 'specific_id');
        const createDoc = await setDoc(docRef, {foo : 'bar'});
       };
      }
      

      谢谢。

      【讨论】:

        猜你喜欢
        • 2020-04-23
        • 1970-01-01
        • 2018-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-19
        • 2018-04-18
        • 1970-01-01
        相关资源
        最近更新 更多