简体   繁体   中英

How to update a value in Firestore database from within a where clause? Swift

I have a database of users and each user has certain values that I would like to be able to update at any time.

For example in the document there are 'calories' ("user" -> unique user document ID -> "calories") that has a set value of 0. I would like to change this when the user input's their own calorie value.

However, with updateData I would need to know the randomly generated document ID like so:

db.collection("user").document(unique user document ID).setData(["calories" : 100])

Currently, to access the current user's data I have this:

        
        let curUser = Auth.auth().currentUser

        let uUid = curUser!.uid

        let db = Firestore.firestore()

        db.collection("user").whereField("uid", isEqualTo: uUid).getDocuments() {(Qsnapshot, error) in
            if let error = error {
                print("Error getting document \(error)")
                
            } else {

                 // Code to change a value in here
 
                
                }
        }

The method above works perfectly for reading data, but I'm not sure it is possible for changing data? Is there a way of finding out the document ID or changing it without needing it ?

If you don't know the document ID, you can't update the document. You would have to query the collection for the document using something you know about the contents of that document, then use the query results to build the path to the document to update.

It's generally not a good idea to just throw documents into Firestore without a strategy for getting them out. If you have per-user data, you should use a per-user unique ID (such as those provided by Firebase Authentication) to store documents related to the user, so that the app can query for the document for just that user. Also, if you need to use the ID of a document that was created, you might want to also store that in the client app for later use.

If the name of the document is the user's uid then you can access the document via db.collection("user").document(uUid) . Because UIDs are unique identifiers, your QuerySnapshot should only ever return a single document, and that document will be at the path /user/uUid/ , so I'm not sure why you're accessing it like that. Unless you have the UID as a field within the document?

In any event, you answered the question yourself:

Access the document with db.collection("user").document(uUid) and do a setData() call

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