【问题标题】:Is there a way to check a firestore document if its certain field is equivalent to some value?如果某个字段等于某个值,有没有办法检查 Firestore 文档?
【发布时间】:2021-12-19 10:01:38
【问题描述】:

我有一个验证产品的功能,正如您在这个 sn-p 中看到的那样:

private fun validateProduct() : Boolean{

        val newProductName = binding.etNewProductName.text.toString().trim()
        val newProductPrice = binding.etNewProductPrice.text.toString().trim()
        val newProductCategory = binding.spNewProductCategory.selectedItem.toString()



        return when{
            TextUtils.isEmpty(newProductName) -> {
                showErrorSnackBar(binding.root, "Product name cannot be empty.", true)
                false

            }
            TextUtils.isEmpty(newProductPrice) -> {
                showErrorSnackBar(binding.root, "Price cannot be empty.", true)
                false
            }

            //make sure the first element is not a valid category
            newProductCategory == binding.spNewProductCategory.getItemAtPosition(0) -> {
                showErrorSnackBar(binding.root, "Please select a valid category.", true)
                false
            }

            //check if the new product's name already exists in the Firestore collection.
            //if so, return false.

 


            else -> {
                true
            }

        }
    }

编辑: 我的逻辑是遍历文档。检查每个文档 if document["name"].toString() == newProductName 如果是,则返回 false 并显示错误小吃栏。

【问题讨论】:

    标签: android firebase kotlin google-cloud-platform google-cloud-firestore


    【解决方案1】:

    有没有办法检查 Firestore 文档的某个字段是否等于某个值?

    当然,有。正如您已经说过的,是的,您必须遍历集合,但不是来获取所有文档并在客户端检查新产品名称。您必须在查询中执行此操作。假设您有一个名为“products”的集合,要检查特定产品名称是否已存在,请使用以下代码行:

    val db = FirebaseFirestore.getInstance()
    val productsRef = db.collection("products")
    Query queryByProductName = productsRef.whereEqualTo("productName", newProductName)
    queryByProductName.get().addOnCompleteListener { task ->
        if (task.isSuccessful) {
            if (!task.result.isEmpty) {
                Log.d(TAG, "$newProductName already exists.")
            } else {
                Log.d(TAG, "$newProductName doesn't exist.")
            }
        } else {
            Log.d(TAG, "Error getting documents: ", task.exception)
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多