【问题标题】:Flutter & Firebase : How can I put the documentID into the document field the moment I just create the document? [duplicate]Flutter & Firebase:如何在我刚创建文档时将 documentID 放入文档字段? [复制]
【发布时间】:2020-10-15 07:13:26
【问题描述】:

Flutter & Firebase : 如何在我刚刚创建文档时将 documentID 放入文档字段中?

通常情况下,如果我们创建文档而不指定 documentID,firebase 会为我们生成一个 ID,对吧?

就我而言,我希望 firebase 为我生成 ID,然后将该 ID 放入文档字段之一。我该怎么做?

await feedbackCollection.document().setData({
      'comment' : comment,
      'feedback_id' : ????,
    });

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:
    DocumentReference docRef = await feedbackCollection.document();
        docRef.setData({
          'comment' : comment,
          'feedback_id' : docRef.id,
        });
    

    【讨论】:

    • 虽然这段代码可能会解决问题,但一个好的答案还应该解释代码的什么以及它如何提供帮助。
    • @BDL,对不起,下次做得更好。因为下面有人已经解释过了。谢谢
    【解决方案2】:
    RaisedButton(
                child: Text('Click Here'),
                onPressed: () async {
                  await FirebaseFirestore.instance
                      .collection('xCollection')
                      .add({'comment': 'comment1'}).then(
                          (DocumentReference docRef) =>
                              docRef.update({'documentID': docRef.id}));
                },
              ),
    

    这样您就可以在xCollection 内创建一个document with Firebase generated ID(您可以更改集合名称),一旦使用必填字段创建文档,它将更新文档,添加一个名为“documentID”的字段并将其 ID 添加到该字段。

    【讨论】:

      【解决方案3】:

      您可以执行以下操作:

      final firestoreInstance = Firestore.instance;
      var docId = firestoreInstance.collection("feedback").document();
      
      await firestoreInstance.collection("feedback").document(docId).setData({
            'comment' : comment,
            'feedback_id' : docId,
          });
      

      使用document()它会生成一个随机id,然后你可以将它分配给一个变量并在创建文档时在字段中使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-05
        • 1970-01-01
        • 2020-01-05
        • 2020-11-08
        • 1970-01-01
        • 2021-05-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多