我有一個功能可以驗證產品,如您在此代碼段中所見:
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 并顯示錯誤小吃欄。
uj5u.com熱心網友回復:
有沒有辦法檢查 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)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/349395.html
標籤:安卓 火力基地 科特林 谷歌云平台 谷歌云firestore
