简体   繁体   English

在 FASTAPI 上使用 PyMongo 将元素插入到嵌套模型 Mongodb 的数组中

[英]Insert an element into an array of nested model Mongodb with PyMongo on FASTAPI

Recently I stuck on inserting an element into an array that held by a parent document.最近,我坚持将一个元素插入到由父文档保存的数组中。 Basically, my model represents a train that can have many wagons.基本上,我的模型代表可以有许多货车的火车。 The wagons is an array that hold a wagon. wagons 是一个装有货车的阵列。

Here is my database model这是我的数据库模型

rom typing import Optional,Union

from pydantic import BaseModel, EmailStr, Field

#Wagon Model
class Wagon(BaseModel):
    no: int = Field(...)
    wagon_code: str = Field(...)
    wagon_type: str = Field(...)
    passengers_on_board: int = Field(...)
    max_capacity: int = Field(...)
    weight: float = Field(...)
    dimension: tuple  = Field(...)

    class Config:
        schema_extra = {
            "example": {
                "no": 3,
                "wagon_code": "GA151-03",
                "wagon_type": "Penumpang",
                "passengers_on_board": 40,
                "max_capacity":80,
                "weight":1050.01,
                "dimension": (20.62,9.91,4.15)
            }
        }

class UpdateWagon(BaseModel):
    no: Optional[int] 
    wagon_code: Optional[str]
    wagon_type: Optional[str]
    passengers_on_board: Optional[int]
    max_capacity: Optional[int]
    weight: Optional[float]
    dimension: Optional[tuple]
    
    class Config:
        schema_extra = {
            "example": {
                "no": 3,
                "wagon_code": "GA151-03",
                "wagon_type": "Penumpang",
                "passengers_on_board": 64,
                "max_capacity":80,
                "weight":1050.01,
                "dimension": (20.62,9.91,4.15)
            }
        }


#Train Model
class Train(BaseModel):
    name: str = Field(...)
    no: str = Field(...)
    first_station: str = Field(...)
    last_station: str = Field(...)
    from_: str = Field(...)
    to_: str = Field(...)
    current_station: str = Field(...)
    position: Optional[tuple]
    wagons: Union[list[Wagon], None] = None

    class Config:
        schema_extra = {
            "example": {
                "name": "Gajayana",
                "no": "GA-151",
                "first_station": "Malang - Kota Baru",
                "last_station": "Jakarta - Gambir",
                "from_":"Malang - Kota Baru",
                "to_":"Malang - Kota Lama",
                "current_station":"Malang - Kota Baru",
                "position": (2.12,2.12),
                "wagons" : [],
                }
        }

class UpdateTrain(BaseModel):
    name: Optional[str]
    no: Optional[str]
    first_station: Optional[str]
    last_station: Optional[str]
    from_: Optional[str]
    to_: Optional[str]
    current_station: Optional[str]
    position: Optional[tuple]
    wagons: Optional[list]

    class Config:
        schema_extra = {
            "example": {
                "name": "Gajayana",
                "no": "GA-151",
                "first_station": "Malang - Kota Baru",
                "last_station": "Jakarta - Gambir",
                "from_":"Malang - Kota Lama",
                "to_":"Kepanjen",
                "current_station":"Malang - Kota Baru",
                "position": (2.08,2.16),
                "wagons": [],
            }
        }

I was using arrayFilters to attach the newly created wagon to the train.我正在使用arrayFilters将新创建的货车附加到火车上。 However, I got no luck to attach the model but a new wagon was created as shown in the function below.但是,我没有运气附加模型,而是创建了一个新的货车,如下面的函数所示。

async def add_wagon(train_no: str,wagon_data: dict) -> dict:
    wagon = await wagon_collection.insert_one(wagon_data)
    new_wagon = await wagon_collection.find_one({"_id": wagon.inserted_id})
    train = await train_collection.find_one({"no": train_no})
    if train:
        train_collection.update_one({"no": train_no},{"$set":{"wagons.$[element]":new_wagon}},array_filters=[{"element":{"$exists":"false"}}],upsert=True)
    return wagon_helper(new_wagon)

The model was served as an API with FASTAPI.该模型作为 API 与 FASTAPI 一起使用。 The operation above was done using PUT method with the route as shown below.上面的操作是使用 PUT 方法完成的,路径如下所示。

@router.put("{train_no}/wagons/", response_description="Wagon data added into the database")
async def add_wagon_data(train_no: str,wagon: Wagon = Body(...)):
    wagon = jsonable_encoder(wagon)
    new_wagon = await add_wagon(train_no,wagon)
    return ResponseModel(new_wagon, "Wagon added successfully")

Is my arrayFilters is wrong ?我的arrayFilters错了吗? or is the way I use $exists as exact equality match is incorrect ?还是我使用$exists作为完全相等匹配的方式不正确?

It turns out I was thinking too complicated.原来我想的太复杂了。 USing $push with upsert=True solve the problem.使用$pushupsert=True解决问题。

async def add_wagon(train_no: str,wagon_data: dict) -> dict:
    wagon = await wagon_collection.insert_one(wagon_data)
    new_wagon = await wagon_collection.find_one({"_id": wagon.inserted_id})
    train = await train_collection.find_one({"no": train_no})
    if train:
        train_collection.update_one({"no": train_no},{"$push":{"wagons":new_wagon}},upsert=True)
    return wagon_helper(new_wagon)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM