如何在Firestore中向文档添加子集合?

时间:2020-05-07 09:43:47

标签: firebase react-native google-cloud-firestore

当前代码

// items is an array.
// Array [
    Object {
      "id": "KQJfb2RkT",
      "name": "first",
    },
    Object {
      "id": "1mvshyh9H",
      "name": "second",
    },
  ]

storeSale = async ({ items }) => {
  this.salesCollection.add({
    status: 1,
    created_at: new Date(),
    updated_at: new Date(),
  });
};

在SalesCollection中添加文档时,我想将项目作为子集合添加到此文档中。

如果您能给我任何建议,我将不胜感激。

我想这样保存。 enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用batched write,如下所示:

// Get a new write batch
let batch = db.batch();

// Set the value of parent
const parentDocRef = db.collection("parentColl").doc();
batch.set(parentDocRef, {
    status: 1,
    created_at: new Date(),
    updated_at: new Date(),
  });

//Set the value of a sub-collection doc

const parentDocId = parentDocRef.id;

const subCollectionDocRef = db.collection("parentColl").doc(parentDocId).collection("subColl").doc();
batch.set(subCollectionDocRef, {
    ...
  });

// Commit the batch
await batch.commit();

需要注意的一个关键点:实际上,从技术角度来看,父集合和该父集合中文档的子集合根本不相关

让我们举个例子:想象一个doc1集合下的col1文档

col1/doc1/

subDoc1(子)集合下的另一个subCol1

col1/doc1/subCol1/subDoc1

这两个文档(以及两个直接的父集合,即col1subCol1)仅共享其路径的一部分,但仅此而已。

这样做的副作用是,如果删除文档,则其子集合仍然存在。

相关问题