【问题标题】:Can I get the generated ID for a document created with batch().set using Firestore?我可以使用 Firestore 为使用 batch().set 创建的文档获取生成的 ID 吗?
【发布时间】: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

【问题讨论】:

  • 是的。您必须在每个操作上实例化您的 ref。换句话说,如果你正在迭代一个对象或数组,你必须在每次迭代时调用doc()

标签: javascript firebase google-cloud-firestore


【解决方案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/…
      猜你喜欢
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多