你可以如何在Python中替换MongoDB中已有的 _id,添加自己的 _id?

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

how can I add my own _id instead of the already given _id in MongoDB in Python?

问题

class ArticleModel(BaseModel):
    _id: int
    title: str
    body: str
    tags: Optional[list] = None
    datetime: Optional[datetime] = None
    caption: Optional[str] = None
    link: Optional[str] = None
    
class Config:
    orm_mode = True
    allow_population_by_field_name = True
    arbitrary_types_allowed = True

@router.post("/article/", status_code=status.HTTP_201_CREATED)
def add_article(article: articleModel.ArticleModel):
    article.datetime = datetime.utcnow()

    try:
        result = Articles.insert_one(article.dict())
        pipeline = [
            {'$match': {'_id': result.inserted_id}}
        ]
        new_article = articleListEntity(Articles.aggregate(pipeline))[0]
        return new_article
    except DuplicateKeyError:
        raise HTTPException(status_code=status.HTTP_409_CONFLICT,
                            detail=f"Article with title: '{article.id}' already exists")
英文:

I have a class model using Pydantics. I try to supply my own ID but it gives me two id fields in the MongoDB database. The one I gave it and the one it makes automatically.

Here is the result of my post method:

你可以如何在Python中替换MongoDB中已有的 _id,添加自己的 _id?

here is my class in models/articleModel.py:

class ArticleModel(BaseModel):
    _id: int
    title: str
    body: str
    tags: Optional[list] = None
    datetime: Optional[datetime] = None
    caption: Optional[str] = None
    link: Optional[str] = None
    
class Config:
    orm_mode = True
    allow_population_by_field_name = True
    arbitrary_types_allowed = True

here is my code for the post method in routers/article_router:

@router.post("/article/", status_code=status.HTTP_201_CREATED)
def add_article(article: articleModel.ArticleModel):
    article.datetime = datetime.utcnow()

    try:
        result = Articles.insert_one(article.dict())
        pipeline = [
            {'$match': {'_id': result.inserted_id}}
        ]
        new_article = articleListEntity(Articles.aggregate(pipeline))[0]
        return new_article
    except DuplicateKeyError:
        raise HTTPException(status_code=status.HTTP_409_CONFLICT,
                            detail=f"Article with title: '{article.id}' already exists")

答案1

得分: 3

我不会翻译代码,以下是您提供的代码中的文本部分的翻译:

I had to change the articleModel to a dictionary and add a new key called _id.

我不得不将articleModel更改为一个字典,并添加一个名为*_id*的新键。

英文:

I had to change the articleModel to a dictionary and add a new key called _id.

@router.post("/article/", status_code=status.HTTP_201_CREATED)
def add_article(article: articleModel.ArticleModel):
    article.datetime = datetime.utcnow()
    
    article_new_id = article.dict()
    article_new_id['_id'] = article_new_id['id']
    del article_new_id['id']

    try:
        result = Articles.insert_one(article_new_id)
        pipeline = [
            {'$match': {'_id': result.inserted_id}}
        ]
        new_article = articleListEntity(Articles.aggregate(pipeline))[0]
        return new_article
    except DuplicateKeyError:
        raise HTTPException(status_code=status.HTTP_409_CONFLICT,
                            detail=f"Article with title: '{article.id}' already exists")

huangapple
  • 本文由 发表于 2023年2月19日 20:26:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500135.html
匿名

发表评论

匿名网友

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

确定