英文:
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:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论