[英]Is there a way to check a firestore document if its certain field is equivalent to some value?
我有一個功能可以驗證產品,如您在此代碼段中所見:
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
}
}
}
編輯:我的邏輯是迭代文檔。 檢查每個文檔,如果 document["name"].toString() == newProductName 如果是,則返回 false 並顯示錯誤小吃欄。
有沒有辦法檢查 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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.