beanie.exceptions.CollectionWasNotInitialized 错误

huangapple go评论87阅读模式
英文:

beanie.exceptions.CollectionWasNotInitialized error

问题

我是新手 Beanie 库,它是一个用于 MongoDB 的异步 Python 对象-文档映射器(ODM)。数据模型基于 Pydantic。

我尝试在 fastAPI 框架中使用这个库,并创建了一个用于某些文档的 ODM,假设它的名称是 SomeClass,然后尝试使用这个 ODM 向数据库中插入一些数据。以下是 ODM 和创建文档的方法的代码(在 someClass.py 中):

from beanie import Document
from pydantic import Field, BaseModel

class SomeClassDto(BaseModel):
    """
    数据传输的类。
    """
    name: str = Field(max_length=maxsize, min_length=1)

class SomeClassDao:
    """
    这是一个包含 'SomeClass' 类(继承自 Beanie Document)以及使用 'SomeClass' 类的方法的类。
    """
    class SomeClass(Document):
        name: str = Field(max_length=20, min_length=1)

    @classmethod
    async def create_some_class(cls, body: SomeClassDto):
        some_class = cls.SomeClass(**body.dict())
        return await cls.SomeClass.insert_one(some_class)

我使用并调用了 create_some_class 函数,但它引发了这个错误:
beanie.exceptions.CollectionWasNotInitialized

然而,错误本身已经很明显,但起初我不理解,也找不到与我的问题相关的问题,因此我决定发布这个问题并回答它,以便将来参考。

英文:

I'm new to the Beanie library which is
> an asynchronous Python object-document mapper (ODM) for MongoDB. Data models are based on Pydantic.

I was trying this library with fastAPI framework, and made an ODM for some document, let's say it's name is SomeClass and then tried to insert some data in the db using this ODM.
Here's the code for ODM and the method to create a document (insomeClass.py):

from beanie import Document
from pydantic import Field, BaseModel
 
class SomeClassDto(BaseModel):
    """
    A Class for Data Transferring.
    """
    name: str = Field(max_length=maxsize, min_length=1)


class SomeClassDao:
    """
    This is a class which holds the 'SomeClass' class (inherited from Beanie Document),
    and also, the methods which use the 'SomeClass'  class.
    """
    class SomeClass(Document):
        name: str = Field(max_length=20, min_length=1)
        

    @classmethod
    async def create_some_class(cls, body: SomeClassDto):
        some_class = cls.SomeClass(**body.dict())
        return await cls.SomeClass.insert_one(some_class)

I've used and called the create_some_class function, but it throwed this error:
beanie.exceptions.CollectionWasNotInitialized

However the error is self-explanatory but I didn't understand at first, and couldn't find any relatable question about my problem in SO, so I decided to post this question and answer it, for the sake of future.

答案1

得分: 2

根据错误提示,我们首先应该初始化集合。我们可以通过 init_beanie 来初始化集合。

我使用这个函数的方式如下(在 databse.py 中):

from beanie import init_beanie
import motor.motor_asyncio
from someClass import SomeClassDao

async def init_db(cls):
    MONGO_DB_DATABASE_NAME = "SomeDBName"
    MOTOR_CLIENT = motor.motor_asyncio.AsyncIOMotorClient()
    DATABASE = MOTOR_CLIENT[MONGO_DB_DATABASE_NAME]
    document_models = [SomeClassDao.SomeClass,]
    await init_beanie(database=cls.DATABASE, document_models=document_models)

然后,我们应该在应用程序启动时使用这个函数,像这样(在 main.py 中):

from fastapi import FastAPI
from database import init_db

app = FastAPI()

@app.on_event("startup")
async def start_db():
    await init_db()
  • 然后,在创建 init_beanie 函数并将要使用的 document 添加到 document_models 后,它就能正常运行,不再出现错误。

希望这有所帮助。

英文:

As the error tells us, we should first Initialize the collection.
We should initialize the collection via the init_beanie.
I’ve used this function like this (in databse.py):

from beanie import init_beanie
import motor.motor_asyncio
from someClass import SomeClassDao

async def init_db(cls):
            MONGO_DB_DATABASE_NAME = "SomeDBName"
            MOTOR_CLIENT = motor.motor_asyncio.AsyncIOMotorClient()
            DATABASE = MOTOR_CLIENT[MONGO_DB_DATABASE_NAME]
            document_models = [SomeClassDao.SomeClass,]
            await init_beanie(database=cls.DATABASE, document_models=document_models)

And then we should use this function at the startup of the app, so we use it like this (in main.py):

from fastapi import FastAPI
from database import init_db

app = FastAPI()
@app.on_event("startup")
async def start_db():
    await init_db()
  • Then after creating the init_beanie function and adding the
    document we want to use to the document_models, it worked without
    error.

Hope this helps.

huangapple
  • 本文由 发表于 2023年2月24日 16:35:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定