我可以使用 Firestore 为使用 batch().set 创建的文档获取生成的 ID 吗?

Posted

技术标签:

【中文标题】我可以使用 Firestore 为使用 batch().set 创建的文档获取生成的 ID 吗?【英文标题】:Can I get the generated ID for a document created with batch().set using Firestore? 【发布时间】:2018-03-26 22:28:20 【问题描述】:

有没有一种方法可以让我为使用 Firestore 作为批处理的一部分创建的文档获取自动生成的 ID?

当使用.add()时,我可以很容易地得到一个ID:

db.collection('posts')
  .add(title: 'Hello World')
  .then(function(docRef) 
    console.log('The auto-generated ID is', docRef.id)
    postKey = docRef.id
);

使用.batch() 我可以添加一个带有.doc().set() 的文档:

const batch = db.batch();

const postsRef = db.collection('posts').doc(postKey);
batch.set(postsRef, title: 'Hello Again, World');

const votesRef = db.collection('posts').doc(postKey)
                   .collection('votes').doc();
batch.set(votesRef, upvote: true)

batch.commit().then(function() 
);

我可以得到添加到votes的文档的自动生成ID吗?

更新:

Doug Stevenson 是正确的 - 我可以通过 votesRef.id 访问 ID

【问题讨论】:

Firestore - batch.add is not a function的可能重复 是的。您必须在每个操作上实例化您的 ref。换句话说,如果你正在迭代一个对象或数组,你必须在每次迭代时调用doc() 【参考方案1】:

为了在创建文档之前自动生成 uid,您可以使用 angularFireAuth 中的 createID() 函数,如下所示:

`

constructor(
    private angularFireStore: AngularFirestore,
   ) 

 const batch = this.angularFireStore.firestore.batch();

 const autogenUid = this.angularFireStore.createId();
 const collectionReference = this.angularFireStore.collection
                            ('collection_name').doc(autogenUid).ref;

 const docData = first_field:'value', second_field:'value2';
 batch.set(collectionReference, docData);

【讨论】:

【参考方案2】:

我也遇到过类似的问题,而且我认为 firestore 的 API 发生了变化。

我收到如下代码错误:

const postsRef = db.collection('posts').doc(postKey);
batch.set(postsRef, title: 'Hello Again, World');

我发现有必要的更改是采用 doc 对象的ref

const postsRef = db.collection('posts').doc(postKey).ref;

希望对大家有帮助!

【讨论】:

【参考方案3】:

当您不带任何参数调用doc() 时,它会立即返回一个具有唯一ID 的DocumentReference,而不向数据库写入任何内容——ID 是在客户端生成的。因此,如果您想要该 id,只需使用该 DocumentReference 上的 id 属性即可。编写该文档后,该 ID 将在数据库中可见。

【讨论】:

我正在关注 Firestore 网络文档示例:var newCityRef = this.afs.collection("cities").doc(); 给了我一个错误“预期 1 个参数,但得到 0”。这完全阻止了我前进。 @FiringBlanks 也许 Angular 的作用与标准的 javascript api 不同? @DougStevenson 看起来他们将其作为必需参数。请参阅此处了解更多信息:github.com/firebase/firebase-js-sdk/blob/… @Edric 您正在查看 Firestore 类上的 doc()。我指的是 CollectionReference 上的 doc()。 github.com/firebase/firebase-js-sdk/blob/…

以上是关于我可以使用 Firestore 为使用 batch().set 创建的文档获取生成的 ID 吗?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Batch 更新 Firestore 中的 500 多个文档?

使用 Batch 对象时云函数停止执行

如何使用swift在firestore文档中的字段中生成空值?

Firestore使用Rest API更新文档字段

我可以在不等待的情况下提交Firestore批量写入吗?

删除 Firestore 集合中的所有文档