Firestore CollectionReference 和 DocumentReference 类型缺少 .add()、.set()、.update() 等方法

Firestore CollectionReference and DocumentReference types missing .add(), .set(), .update(), etc methods

我正在将 Firestore 与 React 和 Typescript 结合使用。我正在尝试从 firestore 获取一些数据并进行更新。 我在网上看到很多使用方法语法的示例,但我的 IDE 显示这些类型没有这些方法。

我可以使用如下函数从 Firestore 获取数据:

import { getFirestore, collection, doc, updateDoc } from 'firebase/firestore';

const firestore = getFirestore(config);

function App() {
  const collRef = collection(firestore, 'collection');
  const docRef = doc(firestore, 'collection/id');
  updateDoc(docRef, { test: 1234 }).then(x => console.log(x));
}

但是我已经看到很多像这样链接方法的例子:

firebase.firestore().collection('collection').doc('id').set({ test: 1234 });

My IDE 表示此链中的 none 类型具有这些方法中的任何一种。 即使 official documentation 也表明引用类型应该具有 .get().set().update() 方法,但它们不存在。

这应该很简单,但我遗漏了一些非常基本的东西。我做错了什么?

您所指的链接方法是较旧的命名空间语法。新的模块化 SDK (v9.0.0+) 使用您的第一个代码片段中的功能语法。

您仍然可以使用兼容版本的旧语法,方法是将导入更改为:

import firebase from "firebase/compat/app"
import "firebase/compat/auth"
// import "firebase/compat/[SERVICE]"

但是,建议将您的代码更新为新语法以获得 tree shaking 的好处。查看 documentation 了解更多信息。