updating specific records in Firebase Firestore

Viewed 37

I'm working on adding keywords to a collection of documents (company information records).

The keyword generation works perfectly but now I'm struggling to figure out why my update isn't working.


with open (file) as csv_file:
    csv_reader=csv.DictReader(csv_file,delimiter=',')
    line_count=0
    for row in csv_reader:
                uuid=row['uuid']
                name=row['name'].lower()
                keywords = ""
                arrName = []
                for c in name:
                    keywords += c
                    arrName.append(keywords)
                print(uuid, arrName)
                data = {
                        u'keywords': arrName}
                doc_ref = store.collection("org_test").where("uuid", "==", uuid).update(data)

I know it's the last line but I get the same error if I use .update or .set.


uuid is: e1393508-30ea-8a36-3f96-dd3226033abd keywords are: ['w', 'we', 'wet', 'wetp', 'wetpa', 'wetpai', 'wetpain', 'wetpaint']

Traceback (most recent call last):
  File "keywords.py", line 107, in <module>
    doc_ref = store.collection("org_test").where("uuid", "==", uuid).update(data)
AttributeError: 'Query' object has no attribute 'update'

I've also tried:

doc_ref = store.collection("org_test").where("uuid", "==", uuid).document.update(data)

But I get a similar error.

2 Answers

You are getting this error because you cannot perform a query and fire an update call from it.

What you are doing in this part of your code:

store.collection("org_test").where("uuid", "==", uuid)

Is returning you a QuerySnapshot object, which is basically the result to a query, and this object does not contain an update() method.

In order to do that, you need to select the document using doc() which returns you a DocumentSnapshot object, and that object is what can trigger the update(), so you can do this in your code:

store.collection("org_test").document(uuid).update(data);

I realized that I had data with different data types. Most of the information can be a string but one is an array.

This was my code and solution. It takes a file name as a command-line argument, parses through the fields, creates an array of keywords based on the company name, and then lastly creates a new collection in my Firestore.

import csv
import argparse
import firebase_admin
import google.cloud
from google.cloud.firestore_v1 import ArrayUnion
from firebase_admin import credentials, firestore

def init_argparse() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description='Parse through the fields, create an array of keywords based on the company name and upload to Firestore.', add_help=False, usage=get_usage())
    parser.add_argument('file', help='File to run against.')
    parser.add_argument('-q', '--quiet', help='Quiet mode', action='store_true')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0.0', help='Version.')
    return parser

# Launch program
if __name__ == '__main__':
    parser = init_argparse()
    args = parser.parse_args()
    arg_quiet = args.quiet
    file = args.file

cred = credentials.Certificate("./serviceAccountKey.json")
app = firebase_admin.initialize_app(cred)

db = firestore.client()

with open (file) as csv_file:
    csv_reader=csv.DictReader(csv_file,delimiter=',')
    line_count=0
    co = []

    for row in csv_reader:

                # Initialize variables
                uuid=row["uuid"]
                name=row["name"].lower()
                primary_role=row["primary_role"]
                cb_url=row["cb_url"]
                domain=row["domain"]
                homepage_url=row["homepage_url"]
                logo_url=row["logo_url"]
                facebook_url=row["facebook_url"]
                twitter_url=row["twitter_url"]
                linkedin_url=row["linkedin_url"]
                combined_stock_symbols=row["combined_stock_symbols"]
                city=row["city"]
                region=row["region"]
                country_code=row["country_code"]
                short_description=row["short_description"]
                keywords = ""
                arrName = []
                clean = []

                # Loop to create searchable keywords
                for c in name:
                    keywords += c
                    arrName.append(keywords)

                doc_ref = db.collection("orgs").document()
                doc_ref.set({
                    u'uuid': uuid,
                    u'name': name,
                    u'keywords': ArrayUnion(arrName),
                    u'primary_role':primary_role,
                    u'cb_url': cb_url,
                    u'domain': domain,
                    u'homepage_url': homepage_url,
                    u'logo_url': logo_url,
                    u'facebook_url': facebook_url,
                    u'twitter_url': twitter_url,
                    u'linkedin_url': linkedin_url,
                    u'combined_stock_symbols': combined_stock_symbols,
                    u'city': city,
                    u'region': region,
                    u'country_code': country_code,
                    u'short_description': short_description
                    })
Related