[Python] GET API request - sub documents

Discussão em 'Python' iniciado por Stack, Fevereiro 16, 2025.

  1. Stack

    Stack Membro Participativo

    so I'm currently creating the backend API for a project. The project has a database that stores posts. Each post has a nested array for comments, and the comments array has another nested array for replies. I've created a GET request to retrieve all replies under a certain comment, however, the same replies are appearing under every comment. Can anyone spot what is wrong with the code?

    Backend code:

    def fetch_all_replies(id, comment_id):

    data_to_return = []
    post = posts.find_one(

    )
    for comment in post["comments"]:
    comment["_id"] = str(comment["_id"])
    for reply in comment["replies"]:
    reply["_rid"] = str(reply["_rid"])
    data_to_return.append(reply)
    return make_response( jsonify( data_to_return), 200 )


    Database structure:

    [
    {
    "_id": "63f4cbb5462827492d6ee419",
    "description": "Join us on a hike of cake hill to see the stunning sunrise!!",
    "comments": [
    {
    "_id": "63f7ba0deca5ad33c3c18ed0",
    "comment": "is this park dog friendly?",
    "replies": [
    {
    "_rid": "63f7fe6e16423c052a18cf8c",
    "comment": "Yeah, this park is dog friendly!",
    "username": "Beth"
    }


    ]


    So if i run the request 'http://localhost:5000/api/v1.0/posts/63f4cbb5462827492d6ee419/comments/63f9ee3194ea5d46da5472c6' I get:

    [
    {
    "_id": "63f9ee3194ea5d46da5472c6",
    "comment": "Do i need much experience to do this hike?",
    "replies": [
    {
    "_rid": "63ff744d03b399e52def7d3d",
    "comment": "Yes, i'm brining my spring spaniel ",
    "username": "sarah"
    }
    ],
    "username": "Rachel"
    }
    ]


    But if I run 'http://localhost:5000/api/v1.0/posts/63f4cbb5462827492d6ee419/comments/63f9ee3194ea5d46da5472c6/replies', I am returned with:

    [
    {
    "_rid": "63f7fe6e16423c052a18cf8c",
    "comment": "Yeah, this park is dog friendly!",
    "username": "Beth"
    },
    {
    "_rid": "63ff74de03b399e52def7d3e",
    "comment": "This is my first hike",
    "username": "Anna"
    },
    {
    "_rid": "63ff752a03b399e52def7d3f",
    "comment": "I've hiked up cave hill several times!",
    "username": "Juno"
    },
    {
    "_rid": "63ff744d03b399e52def7d3d",
    "comment": "Yes, i'm brining my spring spaniel ",
    "username": "sarah"
    }
    ]

    Continue reading...

Compartilhe esta Página