在Firstore节点中无法访问文档密钥

时间:2018-11-23 21:42:41

标签: java android firebase google-cloud-firestore

我在创建用户后写到Firestore,如下所示:

                userMap.put("email", user.getEmail());
                userMap.put("display_name", user.getDisplayName());
                userMap.put("user_id", user.getUid());
                userMap.put("provider", user.getProviders());
                mStoreBaseRef.collection(USERS).add(userMap);

将此用户写入Firestore后,将为该用户生成一个唯一ID。

稍后,我想写入用户节点,但是我没有生成的唯一密钥。我根据用户的特定ID查询“用户”节点,以便可以写入该节点,但是我不确定如何获取该特定用户的密钥:

Query x = mStoreBaseRef.collection(USERS_LABEL).whereEqualTo("user_id", mPollCreatorID);
                x.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        for (DocumentSnapshot d : task.getResult()){
                            User user = d.toObject(User.class);
                            Log.v("USER", user.getUser_id());
                            //I need to add the document here of the unique key
                            mStoreBaseRef.collection(USERS_LABEL).add(followersMap);
                        }
                    }

我正在尝试从下面获取mAQGM9S .......

enter image description here

2 个答案:

答案 0 :(得分:2)

可以通过DocumentSnapshot.getId()获得文档的ID。所以:

Query x = mStoreBaseRef.collection(USERS_LABEL).whereEqualTo("user_id", mPollCreatorID);
x.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        for (DocumentSnapshot d : task.getResult()){
            Log.v("ID", d.getId());
            User user = d.toObject(User.class);
            Log.v("USER", user.getUser_id());
            //I need to add the document here of the unique key
            mStoreBaseRef.collection(USERS_LABEL).add(followersMap);
        }
    }

答案 1 :(得分:1)

您要的是该文档的push id。为此,您应该使用getId()方法。这是您可以执行的操作:

    Query x = mStoreBaseRef.collection(USERS_LABEL).whereEqualTo("user_id", mPollCreatorID);
    x.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            for (DocumentSnapshot d : task.getResult()){
                User user = d.toObject(User.class);
                //Getting push id
                String pushId = d.getId();
                Log.v("USER", pushId);

                //... 
            }
        }

尝试一下,让我们知道它是否有效。