如果集合不存在则创建集合

时间:2021-03-29 21:11:54

标签: android kotlin google-cloud-firestore

如果 firestore 中不存在该集合,我将尝试创建该集合。

我的代码如下

 val docRef = fbase.collection("cities").document("LA")
    docRef.get().addOnSuccessListener {
            document ->
        if(document!= null){
            Toast.makeText(this, "Already exists", Toast.LENGTH_LONG).show()
        }
        else{
            FireBaseRepository 
            Toast.makeText(this, "Does not exists", Toast.LENGTH_LONG).show()
        }
    }

'FireBaseRepository' 只是一个带有初始化集合的类。由于 FirebaseFirestore.java 类确保集合不能为空,我的代码总是通过 if 条件。我已经查看了推荐链接 https://firebase.google.com/docs/firestore/query-data/get-data?hl=en

 @NonNull
  public CollectionReference collection(@NonNull String collectionPath) {
    checkNotNull(collectionPath, "Provided collection path must not be null.");
    ensureClientConfigured();
    return new CollectionReference(ResourcePath.fromString(collectionPath), this);
  }

1 个答案:

答案 0 :(得分:0)

您必须检查以下代码

        if(!document.exists()){
            Toast.makeText(this, "Does not exists", Toast.LENGTH_LONG).show()
            FireBaseRepository
        }
        else{
            Toast.makeText(this, "Already exists", Toast.LENGTH_LONG).show()
        }