如何获得扑朔迷离中的Firestore文档的证件编号

时间:2020-07-18 12:18:12

标签: firebase flutter dart google-cloud-firestore

我尝试了以下操作,但是它返回了Firestore中不存在的随机字符串。 我确实使用查询快照获取了父集合的documentid

DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();

                    var doc_id2=doc_ref.documentID;

更多代码: 我在尝试访问文档ID时遇到错误。我曾尝试使用await但它给出了错误。

 Widget build(BuildContext context) {
        return Scaffold(
          appBar: new AppBar(
            title: new Text(
              "National Security Agency",
              style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.normal,
                  fontSize: 24.0),
            ),
            backgroundColor: Colors.redAccent,
            centerTitle: true,
            actions: <Widget>[
              new DropdownButton<String>(
                items: <String>['Sign Out'].map((String value) {
                  return new DropdownMenuItem<String>(
                    value: value,
                    child: new Text(value),
                  );
                }).toList(),
                onChanged: (_) => logout(),
              )
            ],
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
    
            },
            child: Icon(Icons.search),
          ),
    
          body: StreamBuilder (
              stream: cloudfirestoredb,
    
    
                  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData) return new Text('Loading...');
    
                    return new ListView(
                      children: snapshot.data.documents.map((document) {
    
    
                        var doc_id=document.documentID;
                        var now= new DateTime.now();
                        var formatter=new DateFormat('MM/dd/yyyy');
                        String formatdate = formatter.format(now);
                        var date_to_be_added=[formatdate];
    
                        DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();
    
                       var doc_id5= await get_data(doc_ref);
    
    
                        print(doc_id);
                        
    
    
                        Firestore.instance.collection("board").document(doc_id).collection("Dates").document(doc_id5).updateData({"Date":FieldValue.arrayUnion(date_to_be_added)});
                        return cardtemplate(document['Name'], document['Nationality'], doc_id);
    
                        }).toList(),
                    );
                  },
           ),
              );
      }

5 个答案:

答案 0 :(得分:4)

您必须检索该文档以获取其ID。

尝试一下

callBackMethod(){
   this.props.sendData(value);
 }

请确保您在标记为 async 的函数中使用此代码,因为代码使用了await。

编辑: 在评论中回答您的问题


DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();

                    DocumentSnapshot docSnap = await doc_ref.get();
                     var doc_id2 = docSnap.reference.documentID;

编辑2:

只需将异步添加到地图功能。

Future<String> get_data(DocumentReference doc_ref) async { 
DocumentSnapshot docSnap = await doc_ref.get(); 
var doc_id2 = docSnap.reference.documentID; 
return doc_id2; 
}

//To retrieve the string
String documentID = await get_data();

让我知道这是否可行

答案 1 :(得分:3)

document(),当您不带任何路径调用此方法时,它将为您创建一个随机ID。

从文档中

如果未提供[path],则使用自动生成的ID。 生成的唯一密钥以客户端生成的时间戳为前缀 这样就可以按时间顺序对结果列表进行排序。

因此,如果要获取documentID,请执行以下操作:

var doc_ref = await Firestore.instance.collection("board").document(doc_id).collection("Dates").getDocuments();
doc_ref.documents.forEach((result) {
  print(result.documentID);
});

答案 2 :(得分:2)

您可以通过这种方式在文档中添加值后使用 value.id 获取 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"));
  }

此处value.id 给出了 ducumentId。

答案 3 :(得分:1)

您还可以执行以下操作

Firestore.instance
    .collection('driverListedRides')
    .where("status", isEqualTo: "active")
    .getDocuments()
    .then(
      (QuerySnapshot snapshot) => {
        driverPolylineCordinates.clear(),
        snapshot.documents.forEach((f) {
        
          print("documentID---- " + f.reference.documentID);
         
        }),
      },
    );

答案 4 :(得分:0)

  • 要获取集合中的文档 ID:

    var collection = FirebaseFirestore.instance.collection('collection');
    var querySnapshots = await collection.get();
    for (var snapshot in querySnapshots.docs) {
      var documentID = snapshot.id; // <-- Document ID
    }
    
  • 获取新添加数据的文档ID:

    var collection = FirebaseFirestore.instance.collection('collection');
    var docRef = await collection.add(someData);
    var documentId = docRef.id; // <-- Document ID