简体   繁体   中英

How to check unique alias in cloud firebase?

i want to check nick name in hashmap but i didn't get all document from cloud firebase? How can i do that? Thanks in advance.

val db = Firebase.firestore
val docRef = db.collection("User").document()
docRef.get().addOnSuccessListener { documents->
    
    if (documents != null) {

        val obj= documents.get("Basic Information") as HashMap<*, *>
        val checkNick= obj["nick"].toString()

        if (checkNick == nick){
            Toast.makeText(activity, "exists.", Toast.LENGTH_LONG).show()
        }

    } else {
        Log.d(TAG, "No such document")
    }
}

This line of code creates a reference to a new, non-existing document:

val docRef = db.collection("User").document()

Since the document doesn't exist yet, calling docRef.get() leads to an empty snapshot.


If you want to load a specific document, you'll need to know its document ID and specify that in the call to document :

val docRef = db.collection("User").document("documentIdThatYouWantToLoad")

If you want to check whether any document exists in the collection for the given nickname, you can use a query :

val query = db.collection("User").whereEqualTo("nick", nick)

Since a query can get multiple documents , you also need to handle that differently:

query.get().addOnSuccessListener { documents ->
    if (!documents.empty) {
        Toast.makeText(activity, "exists.", Toast.LENGTH_LONG).show()
    }
    for (document in documents) {
        Log.d(TAG, "${document.id} => ${document.data}")
    }
}
.addOnFailureListener { exception ->
    Log.w(TAG, "Error getting documents: ", exception)
}

Also see:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM