如何在扑扑的Firebase Firestore中获取自动生成的文档ID?

时间:2020-06-12 16:20:21

标签: firebase flutter dart google-cloud-firestore

enter image description here

如何获取此随机生成的文档ID?谢谢您的帮助

3 个答案:

答案 0 :(得分:3)

如果您尝试从Firestore中读取内容,则可以通过执行以下操作来获取整个集合 db.collection("users"),然后为返回的每个文档遍历返回的querySnapshot。您可以通过这种方式获取documentIDHere是它的文档。

db.collection("users").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        var id = doc.id; // randomly generated document ID
        var data = doc.data(); // key-value pairs from the document
    });
});

答案 1 :(得分:2)

添加文档时,您可以获得documentId

  Firestore.instance.collection("users").add(
  {
    "name" : "john",
    "age" : 50,
  }).then((value){
    print(value.documentID);
  });

答案 2 :(得分:0)

看到代码很难给出准确答案,但这是一个选择:

    @Override
    public void onConfigChange(Map<String, String> properties) {

        if (log.isDebugEnabled()) {
            log.debug("ToadContextRefresher invoked, changed keys: {}", properties.keySet());
        }

        // update environment
        MutablePropertySources targetSources = context.getEnvironment().getPropertySources();
        CompositePropertySource compositeSource = (CompositePropertySource) targetSources.get(BOOTSTRAP_PROPERTY_SOURCE_NAME);
        CompositePropertySource newBootstrapSource = new CompositePropertySource(BOOTSTRAP_PROPERTY_SOURCE_NAME);
        //TODO fix
        if(null == compositeSource) {
            return ;
        }

        // shallow copy for non-toad propertySource, swap toad propertySource
        for (PropertySource part : compositeSource.getPropertySources()) {
            if (Objects.equals(part.getName(), TOAD_PROPERTY_KEY)) {
                log.debug("Found toad property source in environment, update it...");
                Map<String, Object> oldProperties = ((MapPropertySource) part).getSource();
                Map<String, Object> newProperties = new HashMap<>(oldProperties);
                newProperties.putAll(properties);
                MapPropertySource newToadSource = new MapPropertySource(TOAD_PROPERTY_KEY, newProperties);
                newBootstrapSource.addPropertySource(newToadSource);
            }
            newBootstrapSource.addPropertySource(part);
        }
        targetSources.replace(BOOTSTRAP_PROPERTY_SOURCE_NAME, newBootstrapSource);

        Set<String> changedKeys = properties.keySet();
        this.context.publishEvent(new EnvironmentChangeEvent(context, changedKeys));
       
        this.scope.refreshAll();
    }

您可以使用listview-builder来创建列表,并在StreamBuilder( stream: Firestore.instance .collection("cars") .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData) { return Center(child: CircularProgressIndicator()); } else { print(snapshot.data.documents[0].documentID) //this prints the document id of the (0th) first element in the collection of cars } }) 属性中,可以使用itemCount:并使用snapshot.data.documents.length通过以下方式访问所有元素的ID:{ {1}}