【问题标题】:How to add additional collection data to document with Cloud Firestore?如何使用 Cloud Firestore 将其他集合数据添加到文档中?
【发布时间】:2021-01-18 11:55:18
【问题描述】:

从 Cloud Firestore(红色)读取数据,该数据是静态数据并本地存储在房间数据库中

private val _fetchedJourneys = MutableLiveData<List<Journey>>()
override val fetchedJourneys: LiveData<List<Journey>>
   get() = _fetchedJourneys

    override suspend fun getJourneys() {
        FirebaseFirestore.getInstance()
                .collection(COLLECTION_JOURNEY)
                .get()
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {

                        val fetchedJourneys = arrayListOf<Journey>()

                        for (queryDocumentSnapshot in task.result!!) {
                            val journey = queryDocumentSnapshot.toObject(Journey::class.java)
                            journey.id = queryDocumentSnapshot.id

                           // At this point I have the journey ID, which in return I  
                           // need to query the progress collection to look for the timestamp and add 
                           // its value it to journey.lastOpened

                            fetchedJourneys.add(journey)
                        }

                        _fetchedJourneys.postValue(fetchedJourneys)

                        Timber.d("Fetched ${fetchedJourneys.size} journeys remotely")

                    } else {
                        Timber.e(task.exception!!.message, "Failed to fetch remote journeys")
                    }
                }

    }

对象:

@Entity(tableName = "journeys")
@IgnoreExtraProperties
@Parcelize
data class Journey(
        @PrimaryKey(autoGenerate = false)
        @SerializedName("journey_id")
        var id: String = "",
        val title: String = "",
        val description: String = "",
        val image: String = "",
        @ColumnInfo(name = "last_opened")
        var lastOpened: String = ""
) : Parcelable

还有一些“进度”数据是动态的,并且因用户而异。 progress 集合中的字段是一个时间戳,必须添加到Journey 对象的lastOpened 属性中,并且位于以 userId 作为 documentId 的文档中。

我是 firebase API 的初学者,我知道所有调用都是异步的,但我似乎想不出一种在调用时将属性“progress”(黄色)添加到对象(红色)的方法到对象。

我可以在应用程序中实现这一点,还是需要重新安排我保存数据的方式?

【问题讨论】:

  • 为了更好地理解,请改写问题。进步不是财产

标签: kotlin mvvm google-cloud-firestore android-livedata kotlin-coroutines


【解决方案1】:

你用黄色勾勒的不是“财产”。那将是一个子集合。您可以在其下嵌套更多文档,就像您已经使用“章节”一样。

没有用于创建子集合的 API。正常开始往里面写文档,需要的时候会创建。

如果您想为文档添加额外的字段,就像您已经在描述和图像中一样,那么您只需在对该文档的引用上调用 update()

【讨论】:

  • 我的意思是一个对象的属性。我检索对象,然后用它的 ID 检索进度。然后将其添加到对象中。
  • Firestore 没有属性和对象。它有集合、文档和字段。您在 Firestore 中建模的所有内容都应围绕这些概念。
  • 但在本地,它是我在 kotlin android 应用程序中使用的对象。我从 firebase 读取它并将其存储在设备上(Android Room)。
  • 也许您想编辑问题以显示您拥有的代码未按您预期的方式工作,并添加有关您尝试使用该代码完成的工作的更多详细信息。归根结底,您必须使用集合、文档和字段才能使数据库中的内容有意义。
  • 我添加了更多信息。希望这可以帮助:)
猜你喜欢
  • 2018-05-10
  • 2020-01-05
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
相关资源
最近更新 更多