在子集合中添加具有自动生成的 ID 的文档?

Add document with auto-generated ID in sub collection?

我正在尝试使用以下方法在 reviews/something 中添加具有自动生成 ID 的文档:

await addDoc(collection(dbFirestore, "reviews", route.params.id), {
  rating: rating,
  text: text,
  user: {
    id: user.id,
    username: user.username,
    avatar: user.avatar,
  },
});

但我得到:

Invalid collection reference. Collection references must have an odd number of segments, but reviews/XXX has 2.

如错误所述,CollectionReference 必须有奇数个路径段,但你有 2 个。你只需要指定集合名称,因此请尝试重构代码,如下所示:

// i.e. remove route.params.id
await addDoc(collection(dbFirestore, "reviews"))

假设 reviews 是一个集合,并且想要将一个文档(具有自动生成的 ID)添加到它的子集合中

await addDoc(collection(dbFirestore, "reviews/document_id/subcollection"), {
  rating: rating,
  text: text,
  user: {
    id: user.id,
    username: user.username,
    avatar: user.avatar,
  },
});