在创建拥有自己的 docId 的文档时,使用 .add() 而不是 .set() 是否有优势?

Is there an advantage of using .add() instead of .set() when creating a doc that holds its own docId?

可以使用 .add().set() 在 Firestore 中创建文档。对于这个特定的问题,我们假设文档拥有一个 属性 和它自己的 docId。

使用 .add() 和以下 .set() 更新的方法:

db.collection("cities").add({
  docId: null,
  name: 'Tokyo',
  country: 'Japan'
});

//... get docId of inserted document via DocumentReference Promise return of add()

//update with docId
db.collection("cities").doc(docId).set(city, {merge: true});

仅使用 set() 的方法:

const newCityRef = db.collection('cities').doc();
// Later...
const res = await newCityRef.set({
  // ...
});

当我想存储一个拥有自己的 docId 的文档时,使用 .add() 有什么特别的优势吗?此外,总是使用 .set() 创建新文档有什么特别的缺点吗?

使用第二种方法时,.doc() 是否总是 return 一个唯一且未使用的 ID?使用第一种方法总是会导致两次写入操作,而仅使用 .set() 只需要一次。

Is there any particular advantage of using .add() when I want to store a document that holds its own docId? Also, is there any particular disadvantage to always creating new documents with .set()?

我相信您已经通过以下有效评估回答了这部分问题:

Using the first approach would always result in two write operations, while only using .set() requires only one.

这意味着在计费方面,您发出的写入次数越多,您需要支付的费用就越多,因为根据实例的位置按每 100,000 个文档的写入次数计费。现在,在实现方面 following section of the docs 揭示了幕后方法本身没有特别的区别:

Behind the scenes, .add(...) and .doc().set(...) are completely equivalent, so you can use whichever is more convenient.

因此,我认为对于您的特定用例,使用 doc() set() 方法可能是最好的方法(以避免由于写入次数而增加计费)。

When using the second approach, does .doc() always return an ID that's unique and unused?

使用 .doc() 必然会创建一个空文档,其中包含一个自动生成的标识符,该标识符是唯一的,正如 doc() method.

参考文献中所建议的那样