【问题标题】:How do you get the document id after adding document in Cloud Firestore in Dart在 Dart 的 Cloud Firestore 中添加文档后如何获取文档 ID
【发布时间】:2018-12-05 20:35:54
【问题描述】:

我使用以下代码使用 Dart/Flutter 更新 Cloud Firestore 集合。

  final docRef = Firestore.instance.collection('gameLevels');
  docRef.document().setData(map).then((doc) {
    print('hop');
  }).catchError((error) {
    print(error);
  });

我试图获取在将文档添加到集合时创建的 documentID,但 (doc) 参数返回为 null。我以为它应该是一个文档引用?

既然是null,我显然不能使用doc.documentID。

我做错了什么?

【问题讨论】:

    标签: dart google-cloud-firestore flutter


    【解决方案1】:

    如果 Dart API 与其他平台类似,document() 方法应该返回一个文档引用,该引用具有一个 id 属性,该属性带有随机生成的即将添加到集合中的文档的 id。

    【讨论】:

    • 它在 Flutter 中的工作方式不同(与 android/ios 相比)。调用 doc() 将返回到文档的路径,它看起来像这样 DocumentReference(rooms/nJxQna0G7Zay4VHvyZz5/messages/c9cI7YjXOy9SMH2NFzEn)
    • 我的错,我忘了打印文档的 ID 变量。应该是正确答案。
    【解决方案2】:

    您可以尝试以下方法:

    DocumentReference docRef = await 
    Firestore.instance.collection('gameLevels').add(map);
    print(docRef.documentID);
    

    由于 add() 方法创建新文档并自动生成 id,因此您不必显式调用 document() 方法

    或者,如果您想使用“then”回调,请尝试以下操作:

      final collRef = Firestore.instance.collection('gameLevels');
      DocumentReferance docReference = collRef.document();
    
      docReferance.setData(map).then((doc) {
        print('hop ${docReferance.documentID}');
      }).catchError((error) {
        print(error);
      });
    

    【讨论】:

    • 如何为我的文档提供自定义 ID?我这样做了,但发生空指针异常 db.collection('users').document(uid).setData(data);数据库中不存在该 ID 的文档。我要添加它
    • 你的语法是正确的。您能否提供准确的错误日志以缩小问题范围?还要检查 uid、数据变量中存在的值,以确保它们不为空。
    【解决方案3】:

    使用value.id,添加到FireStore后即可获取documentId

    CollectionReference users = FirebaseFirestore.instance.collection('candidates');
      
    
          Future<void> registerUser() {
         // Call the user's CollectionReference to add a new user
             return users.add({
              'name': enteredTextName, // John Doe
              'email': enteredTextEmail, // Stokes and Sons
              'profile': dropdownValue ,//
              'date': selectedDate.toLocal().toString() ,//// 42
            })
                .then((value) =>(showDialogNew(value.id)))
                .catchError((error) => print("Failed to add user: $error"));
          }
    

    【讨论】:

      【解决方案4】:

      @Doug Stevenson 是对的,调用 doc() 方法将返回您的文档 ID。 (我使用的是 cloud_firestore 1.0.3)

      要创建文档,您只需调用 doc()。例如,我想在将消息发送到 Firestore 之前获取消息 ID。

        final document = FirebaseFirestore.instance
            .collection('rooms')
            .doc(roomId)
            .collection('messages')
            .doc();
      

      我可以打印并查看文档的 ID。

      print(document.id)
      

      要保存它而不是调用 add() 方法,我们必须使用 set()。

        await document.set({
          'id': document.id,
          'user': 'test user',
          'text': "test message",
          'timestamp': FieldValue.serverTimestamp(),
        });
      

      【讨论】:

      • 我们不能像dart FirebaseFirestore.instance.collection('rooms').doc(roomId).collection('messages') .doc().set({ 'id': doc().id, 'user': 'test user', 'text': "test message", 'timestamp': FieldValue.serverTimestamp(), }); 这样的单一语句中实现它
      猜你喜欢
      • 2021-06-11
      • 2020-12-04
      • 1970-01-01
      • 2018-07-22
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多