【问题标题】:Firebase 9 - how to chain 'addDoc' or similar to a 'collection'?Firebase 9 - 如何链接“addDoc”或类似于“集合”?
【发布时间】:2021-11-15 23:04:21
【问题描述】:

以前在 Firebase 中,您可以像这样添加文档:

const myNewDoc = await db.collection('some-collection-name').add({ //Document details here... });

随着 Firebase 9 的推出,这不再有效。

我想我应该使用导入的.addDoc 方法而不是.add

但我似乎无法将.addDoc 链接到.collection

如果我尝试做这样的事情:

const myNewDoc = await db.collection('some-collection-name').addDoc({ //Document details here... });

TypeScript 抛出此错误:

Property 'addDoc' does not exist on type 'CollectionReference<DocumentData>'.ts(2339)

可以像这样创建更详细的内容:

const someCol = collection(db, "some-collection-name");
const newDoc = await addDoc(someCol, {
    //Document details here...
});

但我宁愿像以前一样“链接”它。

这可能吗?怎么做?

我什至应该使用.addDoc 吗?还是别的什么?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    addDoc() 是 Modular SDK 中的顶级函数。尝试像这样重构您的代码:

    import { collection, addDoc } from "firebase/firestore"; 
    
    const newDoc = await addDoc(collection(db, "some-collection-name"), {
      // Document Data
    });
    console.log("Document written with ID: ", newDoc.id);
    

    documentation 包含名称空间和新语法的示例。


    如果您使用 compat 版本来使用旧语法,那么您必须使用 add() 本身。

    【讨论】:

      猜你喜欢
      • 2019-11-04
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多