个性化阅读
专注于IT技术分析

在Firestore中更新和删除

本文概述

像Firebase实时数据库一样, 我们可以从Firebase Firestore更新和删除值。

更新资料

要在不覆盖整个文档的情况下更新文档的某些字段, 请使用update()方法。此方法以下列方式使用:

val lucknowRef=db.collection("states").document("UP")

//Setting the "isCapital" field of the state 'UP'
lucknowRef.update("capital", true)
	.addOnSuccessListener{Log.d(TAG, "DocumentSnapshot successfully updted")}
	.addOnFailureListener{(e-> Log.w(TAG, "Error updating document", e)}

如果我们的文档包含嵌套对象, 则可以使用“点国家”来引用文档中的嵌套字段。

//Suppose we have the document which contains:
//{
//	name:"Shubham"
//	favorites:{food:"Pizza", color:"Blue", subject:"Physics"}
//	age:21
//}
//For updating age and favorite color:
db.collection("users").document("Shubham")
	.update(mapOf(
            		"age" to 21
             	"favorites.color" to "Red"
))

为了从数组中添加和删除元素, 可以使用arrayUnion()和arrayRemove()方法。 arrayUnion()将元素添加到数组, 但仅添加那些不存在的元素。 arrayRemove()方法删除每个给定元素的所有实例。

val lucknowRef=db.collection("state").document("UP")

//Adding a new region to the "regions" array field automatically.
lucknowRef.update("regions", FieldValue.arrayUnion("greater_virginia"))

//Removing a region to the "regions" array field automatically.
lucknowRef.update("regions", FieldValue.arrayRemove("east_coast"))

删除

在Firebase Firestore中, 要删除文档, 可以使用delete()方法:

db.collection("states").document("UP")
	.delete()
	.addOnSuccessListener{Log.d(TAG, "DocumentSnapshot successfully deleted!")}
	.addOnSuccessListener{e->Log.w(TAG, "Error deleting document", e)}

它不会自动删除其子集合中的文档。我们仍然可以通过引用来访问子集合文档。例如。即使我们删除了/ mycoll / mydoc的祖先文档, 我们也可以通过路径/ mycoll / mydoc // mysubcoll / mysubdoc访问该文档。

如果要删除文档及其子集合中的所有文档, 则必须手动删除。

删除栏位

要从文档中删除特定字段, 请在更新文档时使用FieldValue.delete()方法。

val docRef=db.collection("state").document("UP")

//remove the capital field from the document
val updates=hashMapOf<String, Any>(
	"capital" to FieldValue.delete()
)
doc.Ref.update(updates).addOnCompleteListener{}

删除收藏集

我们必须检索集合或子集合中的所有文档, 并删除它们以删除整个集合或子集合。对于较大的馆藏, 我们可能希望小批量删除文档, 以避免内存不足的错误。

删除集合需要协调无数个单独的删除请求, 并且从移动客户端删除集合会对安全性和性能产生负面影响。

更新/删除

//Creating helper method updateUser
private fun updateUser(name: String, email: String) {
    
    // updating the user via child nodes
    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(email)) {
        val myRef = mFirebaseDatabaseInstance?.collection("users")?.document(userId!!)
        myRef!!.update("name", name)
        myRef.update("email", email)
        
        Toast.makeText(applicationContext, "Successfully updated user", Toast.LENGTH_SHORT)
            .show()
    } else
        Toast.makeText(applicationContext, "Unable to update user", Toast.LENGTH_SHORT).show()
}
//Event handler for update
fun onUpdateClicked(view: View) {

    //Getting value from text field
    val name = username.getText().toString()
    val email = email.getText().toString()

    //Calling helper updateUser method
    updateUser(name, email)
getDataOneTime()

}
//Event handler for delete
fun onDeleteClicked(view: View) {
     
    //Delete user using delete() method
    mFirebaseDatabaseInstance!!.collection("users").document(userId!!).delete()
        .addOnSuccessListener { Toast.makeText(applicationContext, "Successfully deleted user", Toast.LENGTH_SHORT).show() }
        .addOnFailureListener { Toast.makeText(applicationContext, "Unable to delete user", Toast.LENGTH_SHORT).show() }

    // clear information
    txt_user.setText("")
    email.setText("")
    username.setText("")
    FirebaseAuth.getInstance().signOut()
    startActivity(Intent(this, MainActivity::class.java))}
在Firestore中更新和删除
在Firestore中更新和删除
在Firestore中更新和删除
在Firestore中更新和删除
在Firestore中更新和删除

赞(1)
未经允许不得转载:srcmini » 在Firestore中更新和删除

评论 抢沙发

评论前必须登录!