简体   繁体   中英

Swift Firestore Update Field values

In firestore we have added multiple fields without specifying documentID (auto ID). I need to update particular field value, for example:

  1. I'm having list of person details in my collection, which contains name, age and gender
  2. I need to update particular field value where name = kavin

here is my tried code self.DBRef.collection("users").whereField("name", isEqualTo: "kavin") how to update this field value

It's unclear from your question if you expect the name to be unique or if there are many users named "kavin" .

But assuming that the user's name is unique, you might solve it like this

self.DBRef.collection("users")
    .whereField("name", isEqualTo: "kavin")
    .getDocuments() { (querySnapshot, err) in
        if let err = err {
            // Some error occured
        } else if querySnapshot!.documents.count != 1 {
            // Perhaps this is an error for you?
        } else {
            let document = querySnapshot!.documents.first
            document.reference.updateData([
                "age": 99
            ])
        }
    }

You have to make an asynchronous query that will return a QuerySnapshot which has an array of documents as a result. The resulting query does not have any concept of "unique" fields on your documents. So you must handle the logic of what it means if you get more than one result when the name is supposed to be unique.

Once you have retrieved a query result you can directly access a reference to that document with the reference attribute and update the fields that you wanted.

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