Search code examples
pythonfirebasegoogle-cloud-platformgoogle-cloud-firestore

Python firestore does not recognize set function on subcollection


I have a discord bot that is connected to Firebase Firestore. I can get/set data on collections and documents but can't when I try to set on a subcollections.

Here's part of my code:

import discord
from discord import app_commands
from discord.ext import commands
from firebase_admin import firestore
db = firestore.client()

class Upload(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

@app_commands.command(name='upload', description="desc")
    async def upload(self, interaction: discord.Interaction, name: str, file: discord.Attachment):
        
        print(file.url)
        print(interaction.guild.id)
        db_server = db.collection("servers").document(str(interaction.guild.id))
        db_drop_items = db_server.collection("drop_items")
        db_drop_items.set({"name" : name, "image": file.url}, merge=True)
        
        await interaction.response.send_message('Answered')

The issue here is db_drop_items.set is not recognized as a Firestore method and returns this error when executing the command:

enter image description here

But when I try to direct it at the main collection, it works and is added to the database.

db_server = db.collection("servers").document(str(interaction.guild.id))
# db_drop_items = db_server.collection("drop_items")
db_server.set({"name" : name, "image": file.url}, merge=True)

enter image description here

enter image description here


Solution

  • Python Firestore does not recognize the set function on a subcollection.

    That's the expected behavior because the set() function exists inside the DocumentReference class and not inside the CollectionReference class. So if you want to add some data using a CollectionReference object, then you have to call the add() function which:

    Create a document in the Firestore database with the provided data.