0

In the api I'm doing,when a user creates a post,it should return to him the id of it,and when I get all posts it should return the id also,but it's not working that way,sometimes if I use id it works in the schema,or if I use _id it doesn't give an error but does not return it,and by the way I searched and cannot rename _id field

I use fastapi and pydantic and mongoengine

the routes are

@router.get("/", response_model=List[schemas.Post])
def get_posts(limit: int = 10, skip: int = 0, search: Optional[str] = ""):
    posts = (
        Post.objects(type="post").aggregate(
            [
                {"$limit": limit},
                {"$skip": skip},
            ]
        )
    )
    print(posts)
    return list(posts)


@router.get("/news", response_model=List[schemas.Post])
def get_news(limit: int = 10, skip: int = 0, search: Optional[str] = ""):
    if limit < 1:
        limit = 1
    posts = Post.objects(type="news").aggregate([{"$limit": limit}, {"$skip": skip}])
    return list(posts)


@router.post("/", status_code=status.HTTP_201_CREATED)  # response_model=schemas.Post)
def create_post(post: schemas.PostCreate):
    new_post = Post(**post.dict())
    new_post._id = str(uuid.uuid4())
    new_post.save()
    return {
        "id": new_post._id,
        "title": new_post.title,
        "content": new_post.content,
        "created_at": new_post.created_at,
        "published": new_post.published,
        "type": new_post.type,
    }

the model is

class Post(mongoengine.Document):
    _id = mongoengine.StringField(default=str(uuid.uuid4()))
    title = mongoengine.StringField(required=True)
    content = mongoengine.StringField(required=True)
    published = mongoengine.BooleanField(required=True, default=True)
    created_at = mongoengine.DateTimeField(default=datetime.datetime.now)
    likes = mongoengine.EmbeddedDocumentListField(Likes)
    dislikes = mongoengine.EmbeddedDocumentListField(Dislikes)
    comments = mongoengine.EmbeddedDocumentListField(Comment)
    type = mongoengine.StringField(required=True, default="post")
    banner = mongoengine.FileField()

    meta = {
        "db_alias": "jc",
        "collection": "posts",
        "indexes": [{"fields": ["$title", "$content"]}],
    }
the schemas are

class PostBase(BaseModel):
    title: str
    content: str
    published: bool = True
    type: Optional[str] = "post"


class PostCreate(PostBase):
    pass


class Post(PostBase):
    _id: str
    created_at: datetime

    class Config:
        orm_mode = True

If anyone could give a help or some thought or something like that I would appreciate a lot!!! thanks for the attention and reading until here

0 Answers0