2017-10-13 24 views

回答

15

您可以分兩步執行此操作:

// Create a ref with auto-generated ID 
var newCityRef = db.collection('cities').doc(); 

// ... 

// Add it in the batch 
batch.set(newCityRef, { name: 'New York City' }); 

.doc()方法不寫什麼到網絡或磁盤,它只是讓你以後可以使用自動生成的ID的參考。

+0

如果我使用'.doc().set()'鏈,它會拋出'TypeError:batch.doc不是一個函數'。 – artooras

+0

是的,不要調用'batch.doc()',因爲你可以看到我在批處理**之外的集合引用**上調用'.doc()'。 –

+0

你是對的,它確實有效。我不知道'.doc()'命令實際上是離線生成一個唯一的ID,即沒有服務器調用,或者至少沒有在我的集合中創建一個空對象,這是我想包括'首先在批處理中添加()'命令。謝謝!我會接受你的回答。 – artooras

1

按照文檔

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

也許這適用於批量呢?

+0

不幸的是,它拋出一個'TypeError:batch.doc不是一個函數'。 – artooras

+0

不,你不需要在新文檔中調用.set()。 – SimonDepelchin